michel's blog

By michel, history, 9 years ago, In English

Can anybody tell me about C++ multimaps. As far as I know you can assign many values to a key but... how do I access to any of theese values?

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
9 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
map<int,set<int, int> > m;
m[key].insert(values);
m[key].find(x)
  • »
    »
    9 years ago, hide # ^ |
    Rev. 3  
    Vote: I like it 0 Vote: I do not like it
    Sorry but I dont get it yet.
    
    I mean for example:
    
    I have 1->2, 2->4, 1->3 and 3->5. That would be as:
    
    key |  values
       1|  {2,3}
       2|  {4}
       3|  {5}
    

    How can I know how many values are assigned to every key and how can I make reference to each of the values a key has?

»
9 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Thanks two of you for help

  • »
    »
    9 years ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    Unfortunately they didn't tell you how to use multimap. Here's an example.

    • »
      »
      »
      9 years ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it

      That's true, their comments were helpful but what i wanted was an example of using multimap. Could you make a comment with the example, my internet provider does not allow me to go that link

      • »
        »
        »
        »
        9 years ago, hide # ^ |
         
        Vote: I like it 0 Vote: I do not like it
        #include <map>
        #include<iostream>
        using namespace std;
        int main() {
        	multimap<int,string> m;
        	m.insert({1,"hello"});
        	m.insert({1,"world"});
        	m.insert({2,"goodbye"});
        	m.insert({3,"spacecows"});
        	
        	cout<<"Number of elements in key 1: "<<m.count(1)<<endl;
        	
        	auto range = m.equal_range(1);
        	for(auto iter = range.first; iter != range.second; iter++) cout<<iter->second<<" ";
        	cout<<endl;
        	return 0;
        }
        
        • »
          »
          »
          »
          »
          9 years ago, hide # ^ |
           
          Vote: I like it 0 Vote: I do not like it

          I see, very ilustrative example. I've never used auto I gess it make the variable get the type that is asigned to it, am I right?

          • »
            »
            »
            »
            »
            »
            9 years ago, hide # ^ |
             
            Vote: I like it 0 Vote: I do not like it

            Yes, the compiler will deduce the type for you. auto is quite a bit shorter to write than pair<multimap<int,string>::iterator,multimap<int,string>::iterator>.

            I recommend reading these two posts (C++11 for programming contests... and C++ Tricks) for some additional info on using C++11 in programming contests.