我尝试使用重载运算符 ==() 在 vector 中查找元素。但是,如果在以下代码中使用 type1
,则输出为 1 和 0(未找到)。使用type2
同时给出1和1。环境是Xubuntu 12.04和g++版本4.6.3。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<string, int> type1;
struct type2: public type1 {};
#define TYPE type1
bool operator== (const TYPE& lhs, const TYPE& rhs) {
return lhs.first == rhs.first;
}
int main()
{
vector<TYPE> vec;
TYPE v1, v2;
v1.first = "abc"; v1.second = 1; vec.push_back(v1);
v2.first = "abc"; v2.second = 2;
cout << (v1 == v2) << endl;
cout << (find(vec.begin(), vec.end(), v2) != vec.end()) << endl;
}
最佳答案
std::pair
有默认值 operator==
在命名空间 std
,这是任意对的模板,比较 first
和 second
领域。该运算符在四种情况之一中被选中,即 find
与 TYPE == type1
.虽然细节有点复杂:
TYPE == type1
实际发生了什么是(如果我错了请纠正我)
v1 == v2
ADL(参数相关名称查找)用于查找operator==
在std
,意味着这个运算符被添加到正常的重载集中。但是,当前翻译单元中的非模板版本仍然优先于模板operator==
来自std
.std::find
调用在std
中实例化,因此查找operator==
直接在std
开始.它会找到一个匹配项(不使用 ADL!),因此不会搜索本应包含 OP 自己的运算符的封闭范围。
对于 TYPE == type2
-
v1 == v2
很简单 - 它直接找到operator==
在封闭的命名空间中。 -
std::find
也在std
中实例化,但是来自主作用域的自定义运算符被添加到使用 ADL 的重载决议集,然后发现它比std
中的更具体.
关于c++ - find() 使用重载运算符==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19187766/