c++ - 模板中的运算符重载

标签 c++ templates

我正在尝试使用 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/

相关文章:

templates - 戈朗。如何使用 html/template 包创建循环函数

c++ - 无法使 C++ 中的私有(private)方法返回指向私有(private)嵌套类的指针

c++ - 多线 Controller 降低高度

c++ - 为什么数据类型 long 支持最大数等于 long long 的?

c++ - 如何将迭代器限制为前向迭代器?

php - Joomla 模板调整模块位置

c++ - 将图像转换为 C 中可用的字节数组?

c++ - 没有 SSL 验证的 HTTPs 对于本地应用程序是否安全?

c++ - 模板类错误 "Expected initializer before ' <' token"

C++:为什么编译器在不使用时实例化模板