我正在尝试使用 std::find 算法,我的第三个参数是重载 == 运算符的 MyPair 类型的对象。但问题是它没有被调用。这是我的代码:
MyPair.h
template<class K, class V> class MyPair;
template<class K,class V>
bool operator==(const MyPair<K,V>& p1, const MyPair<K,V>& p2);
template<class K,class V>
class MyPair:public std::pair<K,V>
{
public:
MyPair(){};
MyPair(const K&x, const V& y) :pair<K, V>(x, y){ cout << "ctor"<< endl; }
template<class K, class V>
friend bool operator==<>(const MyPair<K, V>& p1, const MyPair<K, V>& p2) {
cout<<"called"; return true; }
};
我正在使用 std::find
算法的另一个文件
void WordVector::insert(string word){
MyPair<string, int> p(word, 1);
auto iter = find(wordvec.begin(),wordvec.end(),p);
if (iter == wordvec.end()){
wordvec.push_back(p);
}
else{
++iter->second;
}
}
最佳答案
如果您只是想找到一些特定的配对,为什么不直接使用 find_if
使用适当的谓词?
例如 ( demo ):
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;
int main() {
vector<pair<int,int> > a = { {1,1} , {1,2}, {1,3}};
auto res = find_if(a.begin(), a.end(),
[](pair<int,int> p){ return (p.first == 1 && p.second==3);});
cout<< (*res).first;
return 0;
}
关于c++ - 模板中的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25220448/