在c ++中使用find_if()函数

时间:2011-01-25 15:34:22

标签: c++

我在使用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;
    }
}

2 个答案:

答案 0 :(得分:6)

您需要指定std命名空间:

iter j = std::find_if(j,initial.end(),space);

或者执行上面所做的操作,然后添加using声明:

using std::find_if;

答案 1 :(得分:6)

除了John Dibling提到的using std::find_if以及其他一系列问题(查看getWords方法以及它在传入流中的作用以及返回类型等等)

您的主要问题是您将两个不同的迭代器类型传递给find_if,第一个迭代器是const_iterator - 因为您分配给const_iterator但是第二个迭代器是非常量的,即initial.begin() - 因为initial不是const - 而const /非const迭代器是不同的类型,这就是为什么它找不到{{1}匹配......

相关问题