首页 > 解决方案 > 无法将 std::lower_bound 返回值分配给 vector::iterator

问题描述

传递给函数: const std::vector &xv:

std::vector<float>::iterator lowBound = lower_bound(xv.begin(), xv.end(), x);

std::vector<float>&在我将其更改为之前,该功能运行良好const std::vector<float>&

Lower_bound在编译时返回语法错误说:

no suitable user-defined conversion from "__gnu_cxx::__normal_iterator<const float *, std::vector<float, std::allocator<float>>>" to "__gnu_cxx::__normal_iterator<float *, std::vector<float, std::allocator<float>>>" exists
std::vector<...>::const_iterator std::lower_bound<std::vector<float, std::allocator<float>>::const_iterator, float>(std::vector<...>::const_iterator __first, std::vector<...>::const_iterator __last, const float &__val)

我尝试过更改std::vector<float>::iteratorconst std::vector<float>::iterator并且也尝试过std::vector<const float>::iterator

这些选项似乎都不起作用。

我很抱歉给您带来麻烦,我尝试用谷歌搜索错误,但无法找到答案。

标签: c++vectortypesconstants

解决方案


lower_bound返回一个const_iterator。你需要

std::vector<float>::const_iterator lowBound = lower_bound(xv.begin(), xv.end(), x);

或者简单地说 (C++11)

auto lowBound = lower_bound(xv.begin(), xv.end(), x);

Demo


推荐阅读