c++11: The pit of unordered_map and pair combined

Things are like this,

An error was reported during compiling today. It is very long. The error is reported in the insert operation of std::ordered_map, but it is no problem to replace it with stdmap.

Probably related to std::unordered_map and std::pair, I cut a few paragraphs,

error: no matching function for call to ‘std::pair<key, std::_List_iterator<long long int> >::pair(const key&, std::_List_iterator<long long int>&)’
       return __pair_type(std::forward<_T1>(__x), std::forward<_T2>(__y));
 error: no matching function for call to ‘std::unordered_map<long long int, std::pair<key, std::_List_iterator<long long int> > >::insert(std::pair<long long int, std::pair<key, std::_List_iterator<long long int> > >)’
         auto res_pair = xxx.insert(std::make_pair(key,std::make_pair(key,value)));

The reason for the error is,

The underlying data structure of std::map is a red-black tree,

The bottom layer of std::unordered_map is hash,

And unordered_map does not have a special hash provided to std::pair,

Therefore, if you must use std::pair, replace unordered_map with map. If you don't consider sorting, some performance is lost.

Or pass a hash structure to std::pair.

// unordered_map源码
template<class _Key, class _Tp,
	   class _Hash = hash<_Key>,
	   class _Pred = std::equal_to<_Key>,
	   class _Alloc = std::allocator<std::pair<const _Key, _Tp> > >
class unordered_map
{
    。。。。。
}

Set a hash structure yourself, and then pass it to std::pair

struct pair_hash
{
    template <class T1, class T2>
    std::size_t operator() (const std::pair<T1, T2> &pair) const
    {
        return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
    }
};

int main()
{
    std::unordered_map<std::pair<sd::string, std::string>, int, pair_hash> map_pair;
}

Or use the boost library: boost::hash<>

typedef std::pair<std::string,std::string> self_pair;
std::unordered_map<self_pair,int,boost::hash<self_pair>> unordered_map;

 

Guess you like

Origin blog.csdn.net/ynshi57/article/details/111561740