I wanted to create a variable of the type map<string, vector<string>> , but so that pairs in the dictionary are not stored in ascending order, but in the order they are added to the dictionary. I suppose you need to specify a comparator when creating it or write your own. Just how to do it for the map, I did not find, but digging into the map code did not understand anything. Help me please.

  • one
    @Ternvein, if in the order of addition, then you need std::list<std::pair<>> . In the hash table, they will be just in disarray, as the word unordered hints at - yrHeTaTeJlb
  • As for std::list<std::pair<> > is also not a good substitute for map. We need an example of what OP wants to achieve. - Ternvein
  • The main purpose of std::map is to search by key (associative array). If your order will be determined by the order of addition, then what and what are you going to look for later? If you are not going to search, then std::map is of no use to you. - AnT
  • I want to create a variable which stores: Stop -> list of buses passing through it. It is necessary to check the presence of a stop in the dictionary, add buses to the stop and return the list of buses. Just later, the search will be carried out not by the addition number but by the key. - Alexey
  • @ Alexey, why do you need it "in the order of addition"? - Ternvein

1 answer 1

 class BusStop { public: BusStop() {} BusStop(BusStop & new_bus) { this->data = new_bus.data; } vector<string> & operator[] (string stop) { for (auto &i : data) { if (i.first == stop) return i.second; } pair <string, vector <string>> d{ stop, {} }; data.push_back(d); return data.back().second; } const vector<string> & at(string stop) const { for (auto &i : data) { if (i.first == stop) return i.second; } throw runtime_error("element not found!"); } int count(string stop) const { int count = 0; for (auto &i : data) { if (i.first == stop) count++; } return count; } size_t size() const { return data.size(); } auto begin() const { return data.begin(); } auto end() const { return data.end(); } vector<pair<string, vector<string>>> data; }; 

As a result, I made this class. In order to iterate over a class object, define begin () end (). redefined the rest as in map. It began to work as intended.