I get errors where i use the find_if function. It says no matching function. I did find that others have come through this error, but i couldn't quite understand the replies. Please can some one correct this & explain what the mistakes are? Any help would be greatly appreciated. Thanks in advance.
//Another way to split strings
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using std:开发者_StackOverflow: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;
}
}
Aside from the using std::find_if
as mentioned by John Dibling, and a whole host of other issues (look at getWords
method and what it's doing with the passed in stream, and return type? etc.)
Your main problem is that you are passing in two different iterator types to find_if
, the first iterator is a const_iterator
- because you assign to a const_iterator
, but the second iterator is non const, i.e. initial.begin()
- because initial
is not const - and the const/non const iterators are different types, which is why it won't find find_if
to match...
You need to specify the std
namespace:
iter j = std::find_if(j,initial.end(),space);
Or do what you did above, and add a using
declaration:
using std::find_if;
精彩评论