find_if() 在 const 函数中返回意外的迭代器类型
find_if() returns unexpected iterator type in const function
以下是一些代码的提炼版本,在 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 产生类似的结果。
因为v
在Container::find
中const
(它本身是const
),v.begin()
和v.end()
的类型,因此find_if
的返回类型,是vector<Element>::const_iterator
。
相关文章:
- 为什么这会返回意外值?
- 从 C++ 调用 cURL 命令会返回意外的错误代码,如 1792 和 6656
- C++ 三角函数返回意外值
- 裸__declspec上的 memcpy 返回意外的字节
- 在C 中读取二进制文件会返回意外值
- OpenCL - 内核方法返回意外结果
- C :Bool方法在COUT语句之后返回意外数字
- 数组中的线性搜索返回意外结果
- POW函数为什么返回意外值
- std::min_element 从类对象返回意外结果
- 位NOT运算符返回意外的负值
- std::min_element返回意外结果
- 递归返回意外输出
- C++随机字符串返回意外结果
- 在DLL的基地址处Win API ReadProcessMemory返回意外数据
- OpenCV 'sortIdx' 返回意外结果
- find_if() 在 const 函数中返回意外的迭代器类型
- c++方法有时会返回意外的高值
- 函数返回意外的结构值
- c++ std:: string.Find以布尔表达式返回意外结果