Can two Key Values be same in a Map

22,877

Solution 1

You may want multimap instead of map.

Solution 2

If you want to associate more than one value with a single key, use std::multimap (or std::unordered_multimap) instead of std::map.

In some cases, it can make sense to have a std::map<key_type, std::vector<mapped_type> > instead (personally, I frequently find this preferable).

Solution 3

If you want to store multiple items with the same key, you should use a multimap (also applies to unordered_ variants).

The following should work:

std::multimap<std::string,int> mm;
for( int i = 0; i != 10; ++i )
  mm.insert(make_pair("hello world"), i);

And your multimap should contain ten entries with key "hello world" and 10 different values.

Share:
22,877
payyans4u
Author by

payyans4u

Updated on July 05, 2022

Comments

  • payyans4u
    payyans4u almost 2 years

    I have defined a Map

    boost::unordered_map<"std::string,std::string">m_mapABC ;
    

    And I Store values in it Like m_mapABC[strValue1]=strValue2;

    And Assume that i store 10 entries to the map.In that case can the same Key Value be used to store 10 different Values..or will it be over written every time...I guess it would.
    In that case using std::pair would help i guess.

    std::map<"std::string, std::pair<"std::string", bool>>myMap2
    

    std::pair can have 2 Key Values Equal(I guess I am Right)...What will be the bool value in each case,will it be TRUE in the first case and FALSE the second time or vice-versa?.

    I also heard about std::tuple or boost::tuple where a single Key can be used to Store Different Values.

    I am not very clear about how to iterate through them...i need help