CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2009

    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?


  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Seattle, WA

    Re: C++ Map with multiple data types?

    There are a few possible approaches.

    You can make the mapped type be designed to contain one of several types. A C union, for instance, or a boost::variant or boost::any in the C++ case.

    Alternatively, you can map to a pointer to a base class (or smart pointer, such as a boost::shared_ptr) and then put classes derived from it into the map.

    Which approach is better, or if yet another one should be sought, depends on your high-level requirements.

  3. #3
    Join Date
    Mar 2003
    India {Mumbai};

    Re: C++ Map with multiple data types?

    It depends on the set of data types you want to store. If they are simple, you can make union as advised by Lindley.
    If data types are complex, make a base class, and derive other 'data-type' classes from it. Make an object of map like:
    std::map<int, Base*>
    In this case, however, you need to allocate appropriate class object before inserting to map. Also, you need to delete the class object after you remove element from map. Make the destructor virtual.

    Lindley, not everyone can use boost.
    My latest article: Explicating the new C++ standard (C++0x)

    Do rate the posts you find useful.

  4. #4
    Join Date
    Nov 2009

    Re: C++ Map with multiple data types?

    Thanks a lot!!!!!!!!!!!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.