Thread: Either Or

  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
    39,659
    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.

  3. #3
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    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