unordered_map not unordered

Apr 4, 2012 at 7:51pm
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 <unordered_map>
#include <string>

typedef std::unordered_map<std::string, int> mm;

int main()
{
	mm m;

	m.insert( mm::value_type( "one",   1 ) );
	m.insert( mm::value_type( "two",   2 ) );
	m.insert( mm::value_type( "three", 3 ) );
	m.insert( mm::value_type( "four",  4 ) );

	const auto& end = m.end();
	auto it         = m.begin();
	for(; it != end; ++it)
	{
		std::cout << (*it).second << std::endl;
	}

	std::cin.ignore();
	return 0;
}


expected output:

1
2
3
4


actual output:

3
1
2
4


WTF???
Apr 4, 2012 at 7:54pm
What compiler/implementation of unordered_map?
Apr 4, 2012 at 8:16pm
VS2010 default std lib

EDIT: Just tried it with g++ 4.6.2 (Mingw) , output is different:

2
4
3
1



But i need unique elements and not sorted, how to achive this?
Last edited on Apr 4, 2012 at 8:20pm
Apr 4, 2012 at 8:58pm
I'm fairly certain the output is due to the fact unordered_map is a hashed container. Different hashing algorithms, different output.
Apr 4, 2012 at 9:25pm
std::unordered_map is unordered so don't expect any particular order.
Apr 5, 2012 at 3:46am
But i need unique elements and not sorted, how to achive this?


You have unique elements, and they're not sorted. I think you have achieved that.

If you want the order of insertion preserved, use a vector. You'll have to manually check for duplicates if there's a possibility of them existing, but it'll get the job done.
Last edited on Apr 5, 2012 at 3:46am
Topic archived. No new replies allowed.