繁体   English   中英

插入适用于set但不适用于unordered_set

[英]Insert works with set but not with unordered_set

在下面的代码中:

#include<unordered_set>
#include<iostream>
#include<utility>
#include<string>
#include<set>

using namespace std;

int main()
{
    set<pair<string, string> > g;
    pair<string, string> tmp;
    tmp.first="hello";
    tmp.second="world";
    g.insert(tmp);
}

如果我改变set<pair<string, string> > g; to unordered_set<pair<string, string> > g; 插入对时我收到错误,如:

test1.cpp:15:14: note:   candidate expects 2 arguments, 1 provided
  g.insert(tmp);
              ^

是否有“哈希函数无法为一对定义但仅限于基本数据类型”的行为? 如果我错了,请纠正我,否则请详细说明。 谢谢!

没有标准方法来计算对上的散列。 你应该为你的对提供哈希函数。 例如: -

struct hash_pair {
    inline std::size_t operator()(const std::pair<std::string,std::string> & p) const {
        return // howsoever you want to implement.
    }
};

然后将你的std :: unordered_set声明为: -

std::unordered_set< std::pair<std::string, std::string>,  hash_pair> mySet;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM