The difference between stl::map and boost::unorder_map

Keywords: C++ P4

The map in stl is implemented based on the red-black tree, and when insert elements, the operator < is used to compare the elements and find the location where the elements can be inserted, so the final traversal results are orderly.

Unorder_map in boost is based on hash value to compare elements. Some elements may have the same hash value but different elements, so the hash_value function and operator== need to be defined first. So the result of traversing unorder_map is out of order.

#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 same age of p2 and p3 in map results in p2 being unable to find the insertion location, and eventually there is no p2 in map.

Posted by Jordi_E on Tue, 12 Feb 2019 14:12:17 -0800