alekscooper
alekscooper

Reputation: 831

Why can't I assign one iterator to another in C++?

I'm writing this function

vector<string> SplitIntoWords(const string& s) {
    vector<string> v_str = {};
    string::iterator str_b;
    str_b = begin(s);

    // TODO some action here

    return v_str;
}

and I need to declare an iterator which will be equal to begin of the string s, which is a parameter in my function.

The problem is with the line str_b = begin(s); - the code doesn't compile with it. Why so and how can I fix it?

Upvotes: 3

Views: 547

Answers (2)

jfMR
jfMR

Reputation: 24738

Since s is const-qualified, begin(s) returns a string::const_iterator:

string::const_iterator str_b;
str_b = begin(s);

or better, let auto deduce str_b's type from its initializer:

auto str_b = begin(s);

Upvotes: 5

rafix07
rafix07

Reputation: 20918

s is const object, so

begin(s)

returns string::const_iterator, you cannot assign string::const_iterator to string::iterator. You can fix it by

string::const_iterator str_b;

Upvotes: 4

Related Questions