Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Map Key Sorted According To Insert Sequence

Tags:

c++

stl

Without help from additional container (like vector), is it possible that I can make map's key sorted same sequence as insertion 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();
}
like image 673
Cheok Yan Cheng Avatar asked Jul 27 '26 18:07

Cheok Yan Cheng


2 Answers

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

That said, you should use std::string as your key. Using a const char* as a map key is A Bad Idea: it makes it near impossible to access or search for an element by its key because only the pointers will be compared, not the strings themselves.

like image 173
James McNellis Avatar answered Jul 30 '26 08:07

James McNellis


No. std::map<Key, Data, Compare, Alloc> is sorted according to the third template parameter Compare, which defaults to std::less<Key>. If you want insert sequence you can use std::list<std::pair<Key, Data> >.

Edit:

As was pointed out, any sequential STL container would do: vector, deque, list, or in this particular case event string. You would have to decide on the merits of each.

like image 45
Nikolai Fetissov Avatar answered Jul 30 '26 08:07

Nikolai Fetissov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!