Either Or

This is a discussion on Either Or within the C++ Programming forums, part of the General Programming Boards category; Hey every1, Just wonderin, I want to have a map datastructure where the second element is always an int but ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    17

    Either Or

    Hey every1,

    Just wonderin,

    I want to have a map datastructure where the second element is always an int but the first can be an int, or a string. Is this possible in C++.

    So, something like

    Code:
    std::map <int | std::string, int> my_map
    Is that a possibility? I want to build up a map (or something similar) where each element is the key to some number. The elements will be of two types, either strings or numbers. I won't know beforehand what the percentage of each will be.

    Any help wud be well appreciated.

    Cheers,


    Rob.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,852
    Use a union (or some STL container which acts as a union)?

    Code:
    struct foo {
      enum { isInt, isString } type;
      union {
        int a;
        std::string b;
      };
    };
    std::map < foo, int> my_map
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    I would think it would be easier and better to use two maps, one for the ints and one for the strings.

    Unless the order of your elements is important and sometimes strings come before ints and sometimes after. In that case you'd need a specialized operator< for your struct that holds the union so that it could determine the appropriate order. Another solution would be to have a Key class, then derive a StringKey and an IntKey. Again, you'd have to have a special method that determines which one is less given two generic keys, and you'd have to worry about object lifetime because you wouldn't be able to store the base object directly in the map.

    However, I still think two maps is usually the way to go, because usually you have no reason to sort the keys with ints mixed in with the strings.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21