find_if() 在 const 函数中返回意外的迭代器类型

find_if() returns unexpected iterator type in const function

本文关键字:返回 意外 类型 迭代器 函数 const if find      更新时间:2023-10-16

以下是一些代码的提炼版本,在 g++ 4.8 中产生以下错误:

x.cpp: In member function ‘void Container::find() const’:
x.cpp:11:71: error: 
conversion from ‘__gnu_cxx::__normal_iterator<const Element*, std::vector<Element> >’ to non-scalar type ‘std::vector<Element>::iterator {aka __gnu_cxx::__normal_iterator<Element*, std::vector<Element> >}’ requested vector<Element>::iterator it = find_if(v.begin(), v.end(), f);

这是代码:

#include <algorithm>
#include <vector>
using namespace std;
struct Element{};
struct Functor{ bool operator()(const Element & ){return false;}; };
struct Container{
   vector<Element> v;
   void find() const {
      Functor f;
      vector<Element>::iterator it = find_if(v.begin(), v.end(), f);
   }
};
int main() { return 0; }

删除 find() 函数上的 const 限定符后,错误消失。错误的原因是什么?鼓励参考标准。删除了谓词等的逻辑,以专注于感兴趣的问题。Clang 3.4 产生类似的结果。

因为vContainer::findconst(它本身是const),v.begin()v.end()的类型,因此find_if的返回类型,是vector<Element>::const_iterator