Use of const_iterator

Hello all,

I'm trying to compile the code of Accelerated C++, page 105: the split function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vector<string> split (string& str) {
    vector<string> ret;
    typedef string::const_iterator iter;
    
    iter i = str.begin();
    
    while (i != str.end()) {
        i = find_if (i, str.end(), not_space);
        
        iter j = find_if (i, str.end(), space);
        
        if (i != str.end())
            ret.push_back(string(i,j));
        i = j;
    }
    
    return ret;
}


This code gives the error message "No matching function for the call to 'find_if' ". Now, if I change the typedef to ::iterator instead of const_iterator, the error goes away.

Why can't I use const_iterator in this example? Thanks for all help!
What compiler do you use?

It compiles fine for me (using MinGW GCC 4.8.1)....
I use the compiler that comes with XCode 5 on Mac OS... How can I find its compiler?
> Why can't I use const_iterator in this example?

std::string::begin() is overloaded;

on non-const strings it returns std::string::iterator
and on const strings it returns std::string::const_iterator

http://www.cplusplus.com/reference/string/string/begin/

This is fine:
1
2
3
4
5
6
7
8
9
10
vector<string> split ( const string& str ) // const-correct 
{
    vector<string> ret;
    typedef string::const_iterator iter ;
    iter i = str.begin() ;
    
    // ...
    
    return ret;
}


This too will compile cleanly:
1
2
3
4
5
6
7
8
9
10
vector<string> split ( string& str ) 
{
    vector<string> ret;
    typedef string::const_iterator iter ;
    iter i = /* str.begin() */ str.cbegin() ; // C++11
    
    // ...
    
    return ret;
}
This is fantastic! Thanks for the very fast help!
Topic archived. No new replies allowed.