Make the card key sorted by insertion sequence

Without the help of an additional container (for example, a vector), is it possible that I can make the card key sorted in the same sequence as the insert sequence?

#include <map>
#include <iostream>

using namespace std;

int main()
{
  map<const char*, int> m;
  m["c"] = 2;
  m["b"] = 2;
  m["a"] = 2;
  m["d"] = 2;


  for (map<const char*, int>::iterator begin = m.begin(); begin != m.end(); begin++) {
      // How can I get the loop sequence same as my insert sequence.
      // c, b, a, d
      std::cout << begin->first << std::endl;
  }

  getchar();
}
+3
source share
3 answers

No. A std::map- sorted container; insertion order is not supported. There are a number of solutions that use the second container to maintain the insertion order in response to another related question .

, std::string . const char* - " ": , , .

+6

. std::map<Key, Data, Compare, Alloc> Compare, std::less<Key>. , std::list<std::pair<Key, Data> >.

Edit:

, STL : vector, deque, list string. .

+4

Consider using the container boost :: multi_index instead of std :: map. You can specify both an ordered map index and an unordered sequential index in your container.

0
source

Source: https://habr.com/ru/post/1741703/


All Articles