I need to have a key with multiple values. What datastructure would you recommend?

前端 未结 7 1132
悲哀的现实
悲哀的现实 2021-02-07 10:53

I have an string array filled with words from a sentence.

words[0] = \"the\"
words[1] = \"dog\"
words[2] = \"jumped\"
words[3] = \"over\"
words[4] = \"the\"
word         


        
7条回答
  •  既然无缘
    2021-02-07 11:07

    std::multimap

    The link provides an excellent example. Quoted below:

     int main()
    {
      multimap m;
    
      m.insert(pair("a", 1));
      m.insert(pair("c", 2));
      m.insert(pair("b", 3));
      m.insert(pair("b", 4));
      m.insert(pair("a", 5));
      m.insert(pair("b", 6));
    
      cout << "Number of elements with key a: " << m.count("a") << endl;
      cout << "Number of elements with key b: " << m.count("b") << endl;
      cout << "Number of elements with key c: " << m.count("c") << endl;
    
      cout << "Elements in m: " << endl;
      for (multimap::iterator it = m.begin();
           it != m.end();
           ++it)
       cout << "  [" << (*it).first << ", " << (*it).second << "]" << endl;
    }
    

提交回复
热议问题