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();
}
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

3 Answers3

6

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.

Community
  • 1
  • 1
James McNellis
  • 348,265
  • 75
  • 913
  • 977
4

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 Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • 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. Apr 19 '10 at 08:16
  • 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 Fetissov Apr 19 '10 at 10:41
0

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
  • 11,290
  • 4
  • 32
  • 49