【发布时间】:2014-03-12 04:05:20
【问题描述】:
当我有一个不可复制对象的映射时,为什么我不能使用 == 比较迭代器?我想在迭代器上进行相等测试时,它不需要复制(或移动)实际对象。
#include <iostream>
#include <utility>
#include <map>
using namespace std;
class A {
private:
int i;
public:
A(int i) : i(i) {}
A(A&) = delete;
A(A&& a) : i(a.i) {}
~A() {}
A& operator=(A&) = delete;
bool operator==(const A& a) const { return i == a.i; }
};
int main() {
map<int, A> myMap;
map<int, A>::iterator it = myMap.find(1);
cout << (it == myMap.end()) << endl;
}
此示例编译失败,在cout 行出现错误。
g++ 给出这个错误:
/usr/include/c++/4.8.2/bits/stl_pair.h: In instantiation of ‘struct std::pair<const int, A>’:
test2.cpp:24:27: required from here
/usr/include/c++/4.8.2/bits/stl_pair.h:127:17: error: ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = A]’ declared to take const reference, but implicit declaration would take non-const
constexpr pair(const pair&) = default;
clang++ 给出这个错误:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/bits/stl_pair.h:127:17: error: the parameter for this explicitly-defaulted copy constructor is const, but a member or base requires it to be non-const
constexpr pair(const pair&) = default;
^
test2.cpp:24:14: note: in instantiation of template class 'std::pair<const int, A>' requested here
cout << (it == myMap.end()) << endl;
但是,如果使用map<int, int> 而不是map<int, A>,它确实有效。将const map<int, A> 与map<int, A>::const_iterator 一起使用没有帮助。
我尝试在cppreference 上查找 map::iterator::operator== 的确切签名,(map::iterator 是一个 BidirectionalIterator,它是一个 ForwardIterator,它是一个 InputIterator)但该网站对概念中的确切类型签名。
【问题讨论】:
-
如果你将它与
myMap.end()以外的东西进行比较,会发生这种情况吗? -
此外,将复制构造函数和赋值运算符设为私有以使某些内容不可复制,而不是将它们公开为实际上不起作用的公共方法,这要干净得多。
-
@aruisdante:我似乎无法将其与
myMap.begin()进行比较,或者对其执行其他操作(例如it->first)。我没有将它们公开为“不起作用”的公共方法,而是使用deleted functions -
哦,傻
c++ 11标签。 -
@Datalore 如果您有兴趣,这就是您收到奇怪错误消息的原因:Comparing two map::iterators: why does it need the copy constructor of std::pair? 答案完全不平凡。