我有一个类,它本质上是一个 std::vector<T>
具有一些附加功能。类(class)有find(const T& value )
返回 value
第一次出现索引的方法或-1:
int my::find(const T& value) {
auto iter = std::find(this->data.begin(), this->data.end(), value);
if (iter == this->data.end())
return -1;
return std::distance(this->data.begin(), iter);
}
一切顺利。然后我想创建一个 find()
重载采用任意谓词而不是值 - 我试过:
int my::find(const std::function<bool(const T&)>& pred) {
auto iter = std::find(this->data.begin(), this->data.end(), pred);
...
}
还有:
template <typename P>
int my::find(P&& pred) {
auto iter = ...
}
但这两种情况都无法编译,因为“编译器”试图找到 pred
在 pred
的 vector 中键入值,而不是应用 pred
到值,即当我实例化 my<int>
时我收到如下编译器错误:
/usr/include/c++/5/bits/predefined_ops.h:194:17: error: no match for ‘operator==’ (operand types are ‘int’ and ‘const std::function<bool(const int&)>’)
{ return *__it == _M_value; }
最佳答案
std::find
算法将始终将其第三个参数视为通过 operator==
与给定序列中的元素进行比较的值。您传入的谓词无法与类的 T
实例进行比较,因此会出现编译器错误。
您正在寻找std::find_if
(重载 #3-4),它将谓词作为第三个参数。
关于c++ - 将 std::find 与用户提供的谓词一起使用 - 自制 find() 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55467832/