我无法判断我是否只是在这里缺少明显的东西,但是我似乎无法使find_if工作。

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

bool isspace(char c)
{
    return c == ' ';
}

int main()
{
    string text = "This is the text";

    string::iterator it = find_if(text.begin(), text.end(), isspace);

    cout << *it << endl;

    return 0;
}

我看过这里的示例http://www.cplusplus.com/reference/algorithm/find_if/,它可以编译并运行,但是除了vector-> string之外,我看不到它与程序之间的区别,但是我不明白为什么这样做会有所不同。

我知道cctype对于isspace具有更好的功能,但是我想确保这不会弄乱我。

我的错误:
test.cpp: In function ‘int main()’:
test.cpp:16:68: error: no matching function for call to ‘find_if(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)’
     string::iterator it = find_if(text.begin(), text.end(), isspace);
                                                                    ^
test.cpp:16:68: note: candidate is:
In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from test.cpp:3:
/usr/include/c++/4.8/bits/stl_algo.h:4456:5: note: template<class _IIter, class _Predicate> _IIter std::find_if(_IIter, _IIter, _Predicate)
     find_if(_InputIterator __first, _InputIterator __last,
     ^
/usr/include/c++/4.8/bits/stl_algo.h:4456:5: note:   template argument deduction/substitution failed:
test.cpp:16:68: note:   couldn't deduce template parameter ‘_Predicate’
     string::iterator it = find_if(text.begin(), text.end(), isspace);
                                                                    ^

最佳答案

错误的关键部分是:

test.cpp:16:68: error: no matching function for call to ‘find_if(
    std::basic_string<char>::iterator,
    std::basic_string<char>::iterator,
    <unresolved overloaded function type>)’ // <==

无法解析的重载函数类型!那是因为您定义了:
bool isspace(char );

但是已经有一个名为 isspace :
bool isspace(int );

以及另一个与std::isspace一起引入的名为 using :
template <class charT>
bool isspace(charT, const locale&);

而且模板无法知道您想要哪一个。因此,您可以明确指定它:
string::iterator it = find_if(
    text.begin(),
    text.end(),
    static_cast<bool(*)(char)>(isspace)); // make sure yours gets called

或者,更简单地说,只需更改您的名字。

或者,最简单的方法是删除您的并停止 using namespace std;。这样,isspace明确地准确地引用了您首先要使用的一个函数。

关于c++ - <algorithm>库中的find_if谓词用作函数的功能要求是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27971249/

10-11 16:04