我想使用由 int
、 char
、 char
组成的元组在我的 unordered_map
中。我正在这样做:
#include <string>
#include <unordered_map>
#include <cstring>
#include <iostream>
#include <tuple>
using namespace std;
tuple <int,char,char> kk;
unordered_map<kk,int> map;
int main()
{
map[1,"c","b"]=23;
return 0;
}
但这给了我以下错误:
map.cpp:9:21: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> class std::unordered_map’
map.cpp:9:21: error: expected a type, got ‘kk’
map.cpp:9:21: error: template argument 3 is invalid
map.cpp:9:21: error: template argument 4 is invalid
map.cpp:9:21: error: template argument 5 is invalid
map.cpp:9:26: error: invalid type in declaration before ‘;’ token
map.cpp: In function ‘int main()’:
map.cpp:14:16: error: assignment of read-only location ‘"b"[map]’
我在这做错了什么?
原文由 Xara 发布,翻译遵循 CC BY-SA 4.0 许可协议
unordered_map 的模板参数如下所示:
std::hash
不适用于元组(向下滚动到库类型的标准特化)。因此,您需要提供自己的,如下所示:最后,正如 Benjamin Lindley 已经回答的那样,您需要使用
std::make_tuple
:代码是从 Using a std::tuple as key for std::unordered_map 中获取的,这里是 Live Example 。