How to iterate / count for multimap <string, string>

My class is as follows:

class Outgoing
{
    multimap<string,string> outgoing;

    public:
    void makeConnection(string key, string value)
    {
        outgoing.insert(pair<string,string>(key,value));
    }

    void iterate()
    {
        multimap<string, string>::iterator it;
        multimap<string, string>::iterator it2;
        pair<multimap<string,string>::iterator,multimap<string,string>::iterator> ret;
        for (it = outgoing.begin();it != outgoing.end();++it)
        {
            ret = outgoing.equal_range((*it));  ??????
            for (it2=ret.first; it2!=ret.second; ++it2)
            {
                ???????

             }
        }
    }
};

background:

I want to introduce a graph that can have many nodes. The key will not be repeated, but may have several meanings.

str1  ----> val1
str1  ----> val2
str2 -----> val3

I want to know how can I get the number of values ​​for a specific key? eg. in the above question for str1 will be 2?

As you can see, I tried to do something after some digging, but in vain.

What is wrong with my code?

thank

EDIT: after the templatetypedef comment, I edited the code:

for (it = outgoing.begin();it != outgoing.end();++it)
{
    cout<< (*it).first << " "<<  outgoing.count((*it).first); 

}

I can get the score, but the key ("str1") appears twice. So the answer that I see is 2 2 1.

I would really appreciate if someone taught me how to iterate this way, I only get one key. BTW, thanks, templatetypedef

+5
2

count, multimap . ,

outgoing.count("str1")

2.

++ multimap. , , :

  • multimap< string, string > map<string, vector<string> >. , , , , vector.

  • , , .

2 - :

for (multimap<string, string>::iterator itr = myMap.begin(); itr != myMap.end(); ) {
    /* ... process *itr ... */

    /* Now, go skip to the first entry with a new key. */
    multimap<string, string>::iterator curr = itr;
    while (itr != myMap.end() && itr->first == curr->first)
        ++itr;
}

, !

+4

equal_range , .

http://www.cplusplus.com/reference/map/multimap/equal_range/

// multimap::equal_range
#include <iostream>
#include <map>

int main ()
{
  std::multimap<char,int> mymm;

  mymm.insert(std::pair<char,int>('a',10));
  mymm.insert(std::pair<char,int>('b',20));
  mymm.insert(std::pair<char,int>('b',30));
  mymm.insert(std::pair<char,int>('b',40));
  mymm.insert(std::pair<char,int>('c',50));
  mymm.insert(std::pair<char,int>('c',60));
  mymm.insert(std::pair<char,int>('d',60));

  std::cout << "mymm contains:\n";
  for (char ch='a'; ch<='d'; ch++)
  {
    std::pair <std::multimap<char,int>::iterator, std::multimap<char,int>::iterator> ret;
    ret = mymm.equal_range(ch);
    std::cout << ch << " =>";
    for (std::multimap<char,int>::iterator it=ret.first; it!=ret.second; ++it)
      std::cout << ' ' << it->second;
    std::cout << '\n';
  }

  return 0;
}
0

All Articles