fork(12) download
  1. #include <map>
  2. #include <ctime>
  3. #include <string>
  4. #include <vector>
  5. #include <iostream>
  6. #include <algorithm>
  7.  
  8. struct MyObject
  9. {
  10. std::string name;
  11. int information;
  12.  
  13. MyObject(const std::string& name, int information)
  14. : name(name), information(information) {}
  15. };
  16.  
  17. int main()
  18. {
  19. std::srand(std::time(0));
  20.  
  21. std::vector<MyObject> dataVec;
  22. std::multimap<std::string, MyObject*> dataMap;
  23.  
  24. // Give each object a random letter
  25. // between A-J as a name and some data
  26. for(auto i = 0; i < 10; ++i)
  27. dataVec.emplace_back(std::string(1, 'A' + std::rand() % 10), i);
  28.  
  29. // Fill dataMap from dataVec
  30. for(auto&& data: dataVec)
  31. dataMap.emplace(data.name, &data);
  32.  
  33. // Select the correct type for calling the equal_range function
  34. decltype(dataMap.equal_range("")) range;
  35.  
  36. // iterate through multimap's elements (by key)
  37. for(auto i = dataMap.begin(); i != dataMap.end(); i = range.second)
  38. {
  39. // Get the range of the current key
  40. range = dataMap.equal_range(i->first);
  41.  
  42. // Now print out that whole range
  43. for(auto d = range.first; d != range.second; ++d)
  44. std::cout << d->first << ": " << d->second->information << '\n';
  45. }
  46. }
  47.  
  48.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
A: 5
A: 7
B: 6
D: 3
E: 0
G: 1
H: 2
H: 4
I: 9
J: 8