Imtiyaz Shaikh
Imtiyaz Shaikh

Reputation: 100

Algorithm not working on const_iterator for non-const object

I am learning C++ from this book called Accelerated C++. A chapter has this function "split" which takes a string read from 'getline' and return a vector filled with separated words.

vector<string> split(string s)
{
    vector<string> ret;
    typedef string::const_iterator iter;

    iter i = s.begin();
    while(i != s.end())
   {   
        i = find_if(i,s.end(),not_space);
        iter j = find_if(i,s.end(),space);

        if(i != s.end())
            ret.push_back(string(i,j));
        i = j;
    }   

    return ret;
}

A slight difference is that the book version is collecting the string as a const reference. Compiler shows error that the parameters for find_if does not match. But when I change the parameter of split to const or change iterator to non_const it works. I don't understand this behavior. I thought passing a const_iterator just means that the function receiving it can't modify the object. The object itself can be non_const in the passing fucntion. Please explain someone.

Upvotes: 0

Views: 165

Answers (1)

Tanveer Badar
Tanveer Badar

Reputation: 5523

i is a constant iterator, but it is initialized with a mutable iterator. That is a valid conversion. But no such conversion happens for second parameter of find_if(), it is value returned by non-const string::end(), hence the type mismatch in template parameter deduction.

Either of the changes you mentioned makes both iterators of the same type; const or non-const. Template parameter deduction proceeds without issue in such a case.

Upvotes: 2

Related Questions