考虑以下代码。由整数和整数 vector 组成的元组被定义为映射的键。然而,令我惊讶的是,当插入或查找由整数和 integer 作为键的元组时,编译器不会抛出任何错误。这怎么可能,因为元组的第二个元素应该是整数 vector 类型?
std::map <boost::tuple<int, vector<int > >, int> test;
std::map <boost::tuple<int, vector<int > >, int>::iterator test_it;
vector <int> t;
t.push_back(4);
test.insert(make_pair(boost::make_tuple(3, t), 4));
test.insert(make_pair(boost::make_tuple(3, 6), 4));
test_it = test.find(boost::make_tuple(3, 7));
if(test_it != test.end())
throw " test is passed";
最佳答案
似乎是 Boost 和许多 C++ 标准库实现中的错误。 pair
双方都存在这个问题和 tuple
.最简单的演示代码是:
#include <vector>
#include <utility>
using namespace std;
int main() {
//compiles
pair<int,vector<int>> bug1( pair<int,int>(5,6) );
//compiles
pair<int,vector<int>> bug2;
bug2 = pair<int,int>(5,6);
}
Clang 4.0 libc++
另一个接受了这个,Comeau Online 也接受了。 GCC 4.7.1 报错。
它不能编译,根据:
20.3.2/12
template<class U, class V> pair(const pair<U, V>& p);
Remark: This constructor shall not participate in overload resolution unless const U& is implicitly convertible to first_type and const V& is implicitly convertible to second_type.
20.3.2/23
template<class U, class V> pair& operator=(const pair<U, V>& p);
Requires:
is_assignable<first_type&, const U&>::value
istrue
andis_assignable<second_type&, const V&>::value
istrue
.
关于c++ - std::map 键的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12214134/