tags:

views:

81

answers:

3

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();
}
+4  A: 

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.

James McNellis
Thanks. Seems like a duplicated question.
Yan Cheng CHEOK
+3  A: 

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.

Nikolai N Fetissov
Iiiirrk. And yet another developer recommends a `list`. Neil will bash you on the head if he ever hears of this. Hint: you'd better recommend a `vector` or a `deque`, there is absolutely no requirement here that would suggest using a `list` is ever remotely useful.
Matthieu M.
There's no requirement to use vector either. At some point one has to learn to make one's own decisions and not just listen to Neil.
Nikolai N Fetissov
A: 

Consider using a boost::multi_index container instead of a std::map. You can put both an ordered map index and an unordered sequential index on your container.

frankc