String constructor and iterator

New to C++, and I'm not understanding this problem I've got: when using the code

1
2
3
    string text = "some words here";
    string::const_iterator where = find(text.begin(), text.end(), ' ');
    cout << string(text.begin(), where);


I'm getting an error message, about some initialisation of string. But when leaving off the "const" in const_iterator and thus getting the code

1
2
3
    string text = "some words here";
    string::iterator where = find(text.begin(), text.end(), ' ');
    cout << string(text.begin(), where);


it all works again. Why can't I use const_iterator for this example, even if I don't change letters in the `text` string?

Thanks all for all help!
http://www.cplusplus.com/reference/string/string/string/ You are using the 7th constructor.
Since it's a template the constructor can take many types as arguments, but every time it wants exactly two arguments of the same type.

So you can have
1
2
string(const_iterator first, const_iterator last); // Both const_iterator
string(iterator first, iterator last); // Both iterator 

But not a mix of the two, because the contructor wants two of the same type.

begin() returns an iterator, `where` is a const_iterator
Last edited on
>I'm getting an error message, about some initialisation of string.
http://www.cplusplus.com/forum/articles/40071/#msg216270

`text.begin()' and `where' are different types, and for some reason the compiler can't convert an iterator to a const_iterator
Use `text.cbegin()'
Fantastic! This is great help!
Topic archived. No new replies allowed.