我正在尝试编写一个函数,如果字符串中有两个相邻的字符都是两位数,则该函数返回true。但是,有了代码,我不断收到以下形式的奇怪错误:
c:\ mingw \ include \ c++ \ 6.2.0 \ bits \ STL_algo.h:950:21:
必需来自'_ForwardIterator std::__ adjacent_find(_ForwardIterator,_ForwardIterator,_BinaryPredicate)[with _ForwardIterator = __gnu_cxx::__ normal_iterator>; _BinaryPredicate = __gnu_cxx::__ ops::__ Iter_comp_iter]'
因此,我正在寻找一种解决方案,或者以一种不同的方式来解决我已经写的东西。
这是我的代码:
bool deriv2::compare(char a, char b){
if (isdigit(a) == true && isdigit(b) == true){
return true;
}
else return false;
}
bool deriv2::filter(string word){
string::iterator it;
it = adjacent_find (++it, word.end(), compare);
if (it!=word.end()){
return true;
}
return false;
}
最佳答案
根据compare
方法的声明方式,它可能是编译错误的根源。传递的二进制谓词compare
不是成员函数很重要。运行下面的程序的退出代码应为1
。
附带说明一下,在此示例中,filter
函数也可以被设置为static
,但是我将其保留了下来,因此无需在static
函数上使用compare
即可轻松进行复制。
#include <algorithm>
#include <cctype>
#include <string>
struct deriv2
{
static bool compare(char a, char b);
bool filter(std::string const& word) const;
};
bool deriv2::compare(char a, char b)
{
using std::isdigit;
return isdigit(a) && isdigit(b);
}
bool deriv2::filter(std::string const& word) const
{
using std::adjacent_find;
return adjacent_find(word.begin(), word.end(), compare) != word.end();
}
int main()
{
deriv2 d;
return d.filter("ab34cd");
}
关于c++ - 如何在字符串C++中使用neighbor_find,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41572709/