为什么find_if在我的程序中不起作用?

an *_*use 4 c++ syntax

我有一个简单的程序调用std::find_if,我想我已经将前两个参数作为迭代器传递,第三个作为预测传递,但是代码仍然无法编译,任何想法?

#include <string>
#include <cctype>
#include <algorithm>

bool notspace(char ch);
bool space(char ch);

int main()  {
    typedef std::string::const_iterator iter;
    iter i;
    std::string s = "ab c";
    i = std::find_if(i, s.end(),space);
    return 0;
}

bool space(char ch)  {
    return std::isspace(ch);
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

q-isspace.cpp: In function ‘int main()’:
q-isspace.cpp:12:38: error: no matching function for call to ‘find_if(iter&, std::__cxx11::basic_string<char>::iterator, bool (&)(char))’
     i = std::find_if(i, s.end(),space);
                                      ^
In file included from /usr/include/c++/5/algorithm:62:0,
                 from q-isspace.cpp:3:
/usr/include/c++/5/bits/stl_algo.h:3806:5: note: candidate: template<class _IIter, class _Predicate> _IIter std::find_if(_IIter, _IIter, _Predicate)
     find_if(_InputIterator __first, _InputIterator __last,
     ^
/usr/include/c++/5/bits/stl_algo.h:3806:5: note:   template argument deduction/substitution failed:
q-isspace.cpp:12:38: note:   deduced conflicting types for parameter ‘_IIter’ (‘__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> >’ and ‘__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> >’)
     i = std::find_if(i, s.end(),space);
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 8

您将i类型std::string::const_iterator(也未初始化)的类型作为第一个参数传递给std::find_if.然后你传递s.end()它返回一个std::string::iterator.这两个迭代器具有不同的类型,但std::find_if期望它们具有相同的类型.

正确的经验法则是将调用与begin()和配对end()

#include <string>
#include <cctype>
#include <algorithm>

bool notspace(char ch);
bool space(char ch);

int main()  {
    typedef std::string::const_iterator iter;
    iter i,j;
    std::string s = "ab c";
    i = std::find_if(s.begin(), s.end(),notspace);
    j = std::find_if(s.begin(), s.end(),space);
    return 0;
}

bool space(char ch)  {
    return std::isspace(ch);
}

bool notspace(char ch)   {
    return !std::isspace(ch);
}
Run Code Online (Sandbox Code Playgroud)


Tri*_*dle 6

int main()  {
    typedef std::string::const_iterator iter;
    iter i,j;
    std::string s = "ab c";
    i = std::find_if(i, s.end(),notspace);
    j = std::find_if(i, s.end(),space);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你没有把你的i变量搞砸,所以它并没有指向任何东西.这意味着[i, s.end())不会形成有效范围,因此您的调用find_if()将无法正常工作.

试试这个:

i = std::find_if(s.begin(), s.end(), notspace);
Run Code Online (Sandbox Code Playgroud)