今天我写了一个小谓词来查找容器中的匹配符号。

但是我遇到了一个问题:我希望在一个类的const方法中的std::find_if调用中使用这个谓词,在一个容器中搜索这个类的成员。

但我只是注意到std::findconst_iterators都无法操作<=>!

我检查了一些C ++引用,似乎没有接受/返回<=>的<=>或<=>版本。我只是无法理解为什么,因为从我所看到的,这些算法无法修改迭代器引用的对象。

以下是SGI实施中记录的<=>:

  

返回第一个迭代器i   范围[first,last]使得* i ==   值。如果没有,则返回最后   迭代器存在。

有帮助吗?

解决方案

对于给定的容器,

std::findstd::find_if肯定可以在*::const_iterator上运行。您是否偶然看到这些功能的签名,并误解了它们?

template <class InputIterator, class Type>
InputIterator find(InputIterator first, InputIterator last, const Type& val);

请注意,InputIterator此处只是模板类型参数的名称,任何const_iterator都将满足其要求。

或许,您可能会将const(即引用const值的迭代器)与<=>迭代器(即本身<=>的迭代器)混淆?

其他提示

std::findstd::find_if都将迭代器类型作为模板参数,因此它们肯定可以const_iterators上运行。仅举一个简单的例子:

#include <vector>
#include <algorithm>
#include <iostream>
int main() { 
    std::vector<int> x;

    std::fill_n(std::back_inserter(x), 20, 2);
    x.push_back(3);

    std::vector<int>::const_iterator b = x.begin();
    std::vector<int>::const_iterator e = x.end();

    std::vector<int>::const_iterator p = std::find(b, e, 3);

    std::cout << *p << " found at position: " << std::distance(b, p) << "\n";
    return 0;
}

这应该被任何正常运行的C ++编译器接受,并产生如下结果:

3发现位置:20

我刚遇到同样的问题。我有一个在成员向量上调用find_if的成员函数,当我尝试创建成员函数时,编译器给了我一个错误const。事实证明,这是因为我将iterator的返回值分配给const_iterator而不是<=>。导致编译器假定<=>的参数也必须<=>而不是<=>,而<=>成员向量无法获取<=>。

如果你出于同样的原因出现在我身边:

error: no matching function for call to ‘find(std::vector<int>::const_iterator, std::vector<int>::const_iterator, int)’

它与const_iterator s没有任何关系。你可能只是忘了#include <algorithm>: - )

我刚刚遇到此代码的问题:

std::string str;
std::string::const_iterator start = str.begin();
std::string::const_iterator match = std::find(start, str.end(), 'x');

错误是<!>“; std :: find <!>”没有匹配的重载。

我需要的修复是使用cend()。令人困惑的是cbegin()不是必需的,我不确定为什么转换是可以的(隐式)而不是end()作为函数参数。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top