运算符==不在模板函数中工作
operator== not working in template function
我正在编写一个模板函数,它接受一个向量和一个结构,并将该结构插入到向量中。但是,如果矢量中有重复的结构,函数将不会插入该结构,因为这些值必须都是唯一的。为了做到这一点,我使用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
值本身。
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中的memset函数工作不正常
- 渲染窗口无法跨多个函数工作
- C++:最大数组值函数工作不正常
- 仅一个功能的链接错误.在同一类和CPP文件中具有相似签名的其他函数工作正常
- 如何让我的构造函数和函数工作,以便我的 main() 能够同时显示字符串和 int 数据
- (c++)无法让 void 函数工作,主.cpp内部的几行也有问题
- 编译器生成的默认构造函数工作 - C++
- 我似乎无法让我的最大长度递归函数工作
- 无法让 SHGetKnownFolderPath() 函数工作
- Qt 5.2无法使qWait函数工作
- 模板作为递归函数工作
- 构造函数工作不正常
- 如何让c风格的字符串函数工作
- 我如何让这个构造函数工作
- C函数工作,c++版本不
- 为什么我的衍生自CRTP函数工作
- 不明白为什么这个C++递归函数工作背后的逻辑
- 对不存在的对象调用成员函数工作正常,c++
- 如何使 cv::setMouseCallback 函数工作