Difference between stl: map and boost: unorder_map, boostunorder_map
The map in stl is implemented based on the red and black trees. When the insert element is used, operator <is used to compare the element and locate the position where the element can be inserted. Therefore, the final traversal result is ordered.
In boost, unorder_map compares elements based on hash values. Some elements may have the same hash value but different elements. Therefore, you must first define the hash_value function and operator =. Therefore, the result of traversing unorder_map is unordered.
#include<string>#include<iostream>#include<map>#include<stdio.h>#include<boost/unordered_map.hpp>using namespace std;struct person{ string name; int age; person(string name, int age) { this->name = name; this->age = age; } bool operator < (const person& p) const { return this->age < p.age; } bool operator== (const person& p) const { return name==p.name && age==p.age; }};size_t hash_value(const person& p){ size_t seed = 0; boost::hash_combine(seed, boost::hash_value(p.name)); boost::hash_combine(seed, boost::hash_value(p.age)); return seed;}map<person,int> m;boost::unordered_map<person,int> um;int main(){ person p1("p1",20); person p2("p2",22); person p3("p3",22); person p4("p4",23); person p5("p5",24); m.insert(make_pair(p3, 100)); m.insert(make_pair(p4, 100)); m.insert(make_pair(p5, 100)); m.insert(make_pair(p1, 100)); m.insert(make_pair(p2, 100)); um.insert(make_pair(p3, 100)); um.insert(make_pair(p4, 100)); um.insert(make_pair(p5, 100)); um.insert(make_pair(p1, 100)); um.insert(make_pair(p2, 100)); for(map<person, int>::iterator iter = m.begin(); iter != m.end(); iter++) { cout<<iter->first.name<<"\t"<<iter->first.age<<endl; } cout<<endl; for(boost::unordered_map<person, int>::iterator iter = um.begin(); iter != um.end(); iter++) { cout<<iter->first.name<<"\t"<<iter->first.age<<endl; } cout<<(m.find(p3)!=m.end())<<endl; return 0;}
Output:
P1 20
P3 22
P4 23
P5 24
P3 22
P1 20
P5 24
P4 23
P2 22
0
Stl: The age of p2 in map is the same as that of p3. As a result, p2 cannot find the insert position. In the end, there is no p2 in map.