C++ STL算法和常量迭代器

C++ STL算法和常量迭代器,c++,stl,iterator,find,constants,C++,Stl,Iterator,Find,Constants,今天我编写了一个小谓词来查找容器中的匹配符号 但我面临一个问题:我想在类的const方法内的std::find_if调用中使用这个谓词,在作为该类成员的容器中搜索 但是我刚刚注意到,无论是std::find还是std::find_,如果能够在const_迭代器上操作 我检查了一些C++引用,似乎没有版本的代码> STD::查找< /COD>或 STD::FIDIVI:< /COD>接受/返回 CONTRORATIORATS/。我只是不明白为什么,因为从我所看到的来看,这些算法无法修改迭代器引用的

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

但我面临一个问题:我想在类的const方法内的
std::find_if
调用中使用这个谓词,在作为该类成员的容器中搜索

但是我刚刚注意到,无论是
std::find
还是
std::find_,如果
能够在
const_迭代器上操作

我检查了一些C++引用,似乎没有版本的代码> STD::查找< /COD>或<代码> STD::FIDIVI:< /COD>接受/返回<代码> CONTRORATIORATS/<代码>。我只是不明白为什么,因为从我所看到的来看,这些算法无法修改迭代器引用的对象

以下是如何在SGI实现中记录
std::find

返回函数中的第一个迭代器i 范围[第一个,最后一个]使*i== 值。如果没有这样的值,则返回last 迭代器存在


std::find
std::find_if
可以对给定容器的
*::const_迭代器进行操作。您是否偶然看到了这些函数的签名,并误解了它们

template <class InputIterator, class Type>
InputIterator find(InputIterator first, InputIterator last, const Type& val);
模板
inputierator find(inputierator first,inputierator last,const Type&val);
请注意,
inputierator
这里只是模板类型参数的名称,任何
const\u迭代器都将满足它的要求


或者,您可能混淆了
常量迭代器
(即引用常量值的迭代器)和
常量迭代器(即本身是
常量的迭代器
)?

std::find
std::find_if
都将迭代器类型作为模板参数,因此它们肯定可以对
const_迭代器进行操作。举个简单的例子:

#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;
}
#包括
#包括
#包括
int main(){
std::向量x;
标准:填充(标准:背面插入器(x),20,2);
x、 推回(3);
std::vector::const_迭代器b=x.begin();
std::vector::const_迭代器e=x.end();
std::vector::const_迭代器p=std::find(b,e,3);

std::cout我刚刚遇到了同样的问题。我有一个成员函数在成员向量上调用
find_if
,当我尝试使成员函数
const
时,编译器给了我一个错误。结果表明,这是因为我将
find_if
的返回值赋给了
迭代器
ins而不是
常量迭代器
。导致编译器假设
find\u if
的参数也必须是
迭代器
,而不是
常量迭代器
,它无法从
常量
成员向量中获取。

如果您出于与我相同的原因来到这里:

error: no matching function for call to ‘find(std::vector<int>::const_iterator, std::vector<int>::const_iterator, int)’
错误:调用“find(std::vector::const_迭代器,std::vector::const_迭代器,int)”时没有匹配的函数

它与
常量迭代器
s没有任何关系。您可能只是忘记了
#包含
:-)

我刚刚遇到了一个关于此代码的问题:

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()则不行作为一个函数参数。

您得到的实际错误是什么?您还可以发布一些示例代码吗?谢谢,实际上,您只是误读了文档,请参阅下面的Pavel的答案。如果您进行测试,您会发现它确实有效。您的问题暗示您有一些代码不起作用-特别是“但我面临一个问题”-实际上,你只是在大声思考。我否决了这个问题,因为如果你尝试过,你会发现它是有效的。哦,我想太晚了,我只是浏览了几十份文档,每次我都读了我想要的,而不是写的x(感谢你的耐心)。