mardi 6 septembre 2022

Using a std::tuple as key for std::unordered_map, cannot find existing key

I want to use tuple as unordered_map key,but sometimes i cannot find the existing key.

#include <iostream>
#include <string>
#include <tuple>
#include <unordered_map>

typedef std::tuple<std::string, std::string, std::string, std::string> key_tuple_t;
struct tuple_hash
{
    template <class T1, class T2, class T3, class T4>
    std::size_t operator()(const std::tuple<T1, T2, T3, T4> &k) const
    {
        return (std::hash<T1>()(std::get<0>(k)) ^ std::hash<T2>()(std::get<1>(k)) ^
               std::hash<T3>()(std::get<2>(k)) ^ std::hash<T4>()(std::get<3>(k)));
    }
};
typedef std::unordered_map<key_tuple_t, std::string, tuple_hash> ResultMap;


void InsetMap(ResultMap& res_map)
{
    auto key = std::make_tuple("ab","cd","ef","gh");
    res_map.insert(ResultMap::value_type(key,"1"));
}
int main()
{
    ResultMap res_map;
    InsetMap(res_map);//inset map


    auto key = std::make_tuple("ab","cd","ef","gh");
    auto iter = res_map.find(key);
    if (iter != res_map.end())
        std::cout<<iter->second<<std::endl;
    else
        std::cout<<"not find"<<std::endl;
}

The main is sample,and it work; but when i read hundrends of data and insert map,i have two key to find, one can be found,another cannot be found. and i confirm that the key hash has already existed by cout the hash, i want to know why sometimes cannot find the existing key.Thanks

Aucun commentaire:

Enregistrer un commentaire