c++ - 将 std::find 与用户提供的谓词一起使用 - 自制 find() 重载

标签 c++

我有一个类,它本质上是一个 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 = ...
}

但这两种情况都无法编译,因为“编译器”试图找到 predpred 的 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/

相关文章:

c++ - _CRT_DEBUGGER_HOOK 抛出异常

c++ - C++ 中的不可变类和内存

c++ - 读写 float 组到文件

c++ - QCoreApplication 什么时候有效?

C++ 虚函数和可执行文件

c++ - 访问 vector 中的结构元素

java - QProcess 不启动 java 应用程序

c++ - 在 C++ 中返回生成的数组

c++ - 使用 std::launder 从指向非事件对象的指针获取指向事件对象成员的指针?

c++ - 灰度图像到单色度?