做从书C++入门,肚里的运动的时候我坚持:std :: find_if_not()返回什么类型?
练习10.24:使用绑定和check_size找到一个 向量整数的具有值大的第一个元素比指定的字符串值 的长度长。
我的代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
bool check_size(const std::string &s, std::string::size_type sz)
{
return s.size() > sz;
}
std::vector<int>::iterator
find_first_bigger(const std::vector<int> &v, const std::string &s);
int main(){return 0;}
std::vector<int>::iterator
find_first_bigger(const std::vector<int> &v, const std::string &s)
{
auto it= std::find_if_not(v.begin(), v.end(),std::bind(check_size,s,std::placeholders::_1));
return it;
}
当试图编译,编译器抱怨说:
error: could not convert 'it' from '__gnu_cxx::__normal_iterator<const int*, std::vector<int> >' to 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}'
要找出到底是怎么回事,我转身头文件* stl_algo.h *其中我猜std :: find_if_not被定义了。那里的评论说:
@return范围@p第一迭代@ci [_ 第一, _Last)
该函数的定义:
template<typename _InputIterator, typename _Predicate>
inline _InputIterator
find_if_not(_InputIterator __first, _InputIterator __last,
_Predicate __pred)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_function_requires(_UnaryPredicateConcept<_Predicate,
typename iterator_traits<_InputIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
return std::__find_if_not(__first, __last, __pred);
}
似乎返回类型应该是一样的论点。但为什么编者抱怨如此?如何解决这个错误?Thx。
'iterator'与'const_iterator'不一样。你不能从一个常量向量中获得一个'iterator'。 – chris
另一个'auto'的滥用? 'auto'对于for循环的控制变量来说很好,其中声明的变量没有在for循环之外的作用域,但是更通常的用法应该被认为是反模式。 –
@chris谢谢..你是对的.. –