使用std :: tuple作为std :: unordered_map的关键字 [英] Using a std::tuple as key for std::unordered_map

查看:2011
本文介绍了使用std :: tuple作为std :: unordered_map的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的代码,我得到一个非常混乱的错误在MSVC似乎建议的键类型(std :: tuple)被转换为std :: string。

With the code below, I get a very confusing error in MSVC that seems to suggest the key type (an std::tuple) is being converted to an std::string.

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

typedef std::tuple<std::string,int,char> key_t;

struct key_hash : public std::unary_function<key_t, std::size_t>
{
   std::size_t operator()(const key_t& k) const
   {
      return std::get<0>(k)[0] ^ std::get<1>(k) ^ std::get<2>(k);
   }
};

struct key_equal : public std::binary_function<key_t, key_t, bool>
{
   bool operator()(const key_t& v0, const key_t& v1) const
   {
      return (
               std::get<0>(v0) == std::get<0>(v1) &&
               std::get<1>(v0) == std::get<1>(v1) &&
               std::get<2>(v0) == std::get<2>(v1)
             );
   }
};

struct data
{
   std::string x;
};

typedef std::unordered_map<key_t,data,key_hash,key_equal> map_t;


int main()
{
   map_t m;
   data d;
   d.x = "test data";
   m[std::make_tuple("abc",1,'X')] = d;
   auto itr = m.find(std::make_tuple(std::string("abc"),1,'X'));
   if (m.end() != itr)
   {
      std::cout << "x: " << itr->second.x;
   }
   return 0;
}

错误:

Error   1   error C2664: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'const std::tr1::tuple<_Arg0,_Arg1,_Arg2>' to 'const std::basic_string<_Elem,_Traits,_Ax> &'  c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\tuple    127 1   

编译器:MS Visual Studio 2010

Compiler: MS Visual Studio 2010

在ideone上,我得到以下更复杂的错误:

On ideone, I get the following even more convoluted error:

http://ideone.com/yEv2j

推荐答案

ideone的问题是 key_t 已存在:

The problem for ideone is that key_t already exists:

prog.cpp:7:42: error: conflicting declaration 'typedef class std::tuple<std::basic_string<char>, int, char> key_t'
/usr/include/sys/types.h:123:17: error: 'key_t' has a previous declaration as 'typedef __key_t key_t'

key_t 重命名为其他值,或将其放入某些命名空间。

Rename your key_t to something else, or put it into some namespaces.

您的代码在此更改后工作在g ++和clang ++中。我相信这是MSVC的一个错误。

Your code works after this change in both g++ and clang++. I believe this is a bug in MSVC.

这篇关于使用std :: tuple作为std :: unordered_map的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆