Thread: C++ Map with multiple data types?

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    7

    C++ Map with multiple data types?

    Hi everyone!

    I'm doing a C++ problem that I'm a bit stuck on.

    I'd like to be able to store multiple data types in a C++ container with a key (such as a Map)...

    Is there any way to do this or another way I should be approaching this?

    Thanks

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    since you can only have one "type", all entries in the map must be of that type. for example, a map with type "string" can only store objects of type "string" (of course).

    the only reason you would want to have the map store "different" types is if they are all related somehow, that is: they all extend some class. maybe you have a map to store objects of type "Vehicle". if you have child classes "Sedan", "Truck", etc, then those can be stored in the same map--because they are related. you wouldnt want to add an "Animal" to your "Vehicle" map because they arent related (of course unless you made them!).

    if you are trying to store different unrelated types (i.e. no parent-child relationship), then its probably a design issue (or this data structure doesnt make sense to use).

    hope it helps.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I agree that putting mixed unrelated types in a container seems a bit strange, but if you really want to, I think using the Boost Any class should work.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Generalising methods to handle multiple weapon types
    By Swarvy in forum Game Programming
    Replies: 2
    Last Post: 05-22-2009, 02:52 AM
  2. Reading a file with Courier New characters
    By Noam in forum C Programming
    Replies: 3
    Last Post: 07-07-2006, 09:29 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM
  5. Data types in Unicode
    By Garfield in forum Windows Programming
    Replies: 12
    Last Post: 10-28-2001, 10:48 AM

Tags for this Thread