运算符==不在模板函数中工作

operator== not working in template function

本文关键字:函数 工作 运算符      更新时间:2023-10-16

我正在编写一个模板函数,它接受一个向量和一个结构,并将该结构插入到向量中。但是,如果矢量中有重复的结构,函数将不会插入该结构,因为这些值必须都是唯一的。为了做到这一点,我使用STL库的find函数,并使用operator==分析返回值。然而,每次我尝试编译时都会出现以下错误:

error: no match for 'operator==' (operand types are 'OneToOneMap' and'OneToOneMap')|

我的模板功能如下:

template<typename Type> void AddToList(vector<Type> add_to, Type to_insert){
    bool contains_element = *find( add_to.begin(), add_to.end(), to_insert) == *add_to.end() ? false:true;
    if(contains_element){
        cout << "Element is already in list" << endl;
    }else{
        add_to.push_back(to_insert);
    }
}

问题还不完全清楚,但我怀疑您没有重载类/结构OneToOneMap中的operator==,您正试图在代码中对其进行比较。假设这是一个用户定义的类型,重载此运算符(和operator!=)如下:

class OneToOneMap {
public:
    //...
    bool operator==(const OneToOneMap& _other) const {
        // do comparison based on fields
    }
    bool operator!=(const OneToOneMap& _other) const {
        return !(*this == _other);
    }
};

编辑

在Ineed中,您需要为要在其上使用std::find<T>()的类型提供重载!原因当然是函数需要一种方法来比较容器元素,以确定它们是否相等。正如班特伯里大主教所注意到的那样,为bool T::operator==(const T& other)提供过载。

(更确切地说,当用户没有提供另一个谓词来比较元素时,会使用bool operator==(...)进行比较,请参阅http://en.cppreference.com/w/cpp/algorithm/find)

原始答案:

在比较迭代器时删除不必要的取消引用运算符*

bool contains_element = find( add_to.begin(), add_to.end(), to_insert) == add_to.end() ? false:true;

您也不需要false : true,因为比较返回bool:

bool contains_element = find( add_to.begin(), add_to.end(), to_insert) == add_to.end();

逻辑是std::find<T>()函数返回一个迭代器,然后将该迭代器与vector<T>::end()迭代器(即"null"迭代器)进行比较,以检查find<T>()是否能够找到任何内容。您不需要比较T值本身。