我在使用 find_if 函数时遇到错误。它说没有匹配功能。我确实发现其他人也遇到过这个错误,但我不太明白回复。请有人可以纠正这个并解释错误是什么?任何帮助将不胜感激。提前致谢。
//Another way to split strings
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using std::endl;
using std::cout;
using std::cin;
using std::string;
using std::vector;
using std::istream;
istream& getWords(istream&, vector<string>&);
string& removeDelimeters(string&);
bool space(char);
bool not_space(char);
void display(const vector<string>&);
int main()
{
vector<string> words;
getWords(cin,words);
display(words);
return 0;
}
void display(const vector<string>& vec)
{
cout<<endl;
for(vector<string>::const_iterator iter = vec.begin();iter != vec.end();iter++)
{
cout<<*iter<<endl;
}
}
bool space(char c)
{
return isspace(c);
}
bool not_space(char c)
{
return !isspace(c);
}
string& removeDelimeters(string& word)
{
string delim = ",.`~!@#$%^&*()_+=-{}][:';?><|";
for(unsigned int i = 0;i<word.size();i++)
{
for(unsigned int j = 0;j<delim.size();j++)
{
if(word[i] == delim[j])
{
word.erase(word.begin()+i); //removes the value at the given index
break;
}
}
}
return word;
}
istream& getWords(istream& in, vector<string>& vec)
{
typedef string::const_iterator iter;
string initial;
cout<<"Enter your initial sentance : ";
getline(cin,initial);
initial = removeDelimeters(initial);
iter i = initial.begin();
while(i != initial.end())
{
//ignore leading blanks
i = find_if(i,initial.end(),not_space);
//find the end of the word
iter j = find_if(j,initial.end(),space);
//copy the characters in [i,j)
if(i != initial.end())
{
vec.push_back(string(i,j));
}
i = j;
}
}
最佳答案
除了 John Dibling 提到的 using std::find_if
和一大堆其他问题(查看 getWords
方法以及它对传递的内容所做的事情)在流中,返回类型?等等)
您的主要问题是您将两个不同的迭代器类型传递给find_if
,第一个迭代器是const_iterator
- 因为您分配到 const_iterator
,但第二个迭代器是非 const,即 initial.begin()
- 因为 initial
不是 const - 而 const/非 const 迭代器是不同的类型,这就是为什么它找不到 find_if
来匹配...
关于c++ - 在 C++ 中使用 find_if() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4795391/