how to get map datastructure elements in the order of insertion
Dec 7, 2009 at 5:58am UTC
Hi,
I'm writing a program to find the first no-repeated character in a string. My idea was to scan the string and store the number of occurrence in a map.
This is my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
string candidate = "total" ;
map<char ,int > chars;
for (int i=0;i<candidate.length();i++)
{
chars[candidate[i]]++;
}
map<char , int >::iterator it;
for (it=chars.begin();it != chars.end(); it++)
{
if ((*it).second == 1)
cout << (*it).first ;
}
cout << endl;
return 0;
}
I expected
oal
as output, but this is what I got,
.
It seems the map data structure sorts the elements. How can I get the elements in the order I inserted into the map.
Thanks.
Dec 7, 2009 at 8:53am UTC
Topic archived. No new replies allowed.