C++ Map with multiple data types?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: C++ Map with multiple data types?

Hybrid View

  1. #1
    Join Date
    Sep 2009
    Posts
    19

    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
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    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
    Location
    India {Mumbai};
    Posts
    3,871

    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:
    Code:
    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
    Posts
    1

    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

This is a CodeGuru survey question.


Featured


HTML5 Development Center