lightning_missile
lightning_missile

Reputation: 2992

Dereferencing char iterator

I am new in c++ and just learned about iterators. I have this code:

//lines is a vector<string>
for (auto it = lines.begin(); it != lines.end(); ++it) {
    //I want to access each characters in each element (string) of the vector
    for (auto it2 = *it->begin(); it2 != *it->end(); ++it2) {
        cout << *it2 << endl; //error: invalid type argument of unary '*' (have 'char')
    }
    cout << *it << endl; //ok
}

I tested asigning the string to a variable:

string word = *it;
for (auto it2 = word.begin(); it2 != word.end(); ++it2) {
    cout << *it2 << endl; //ok
}

My question is why the second code works while the first doesn't? It seems to me that *it2 is a string and I can access the chars inside it using an iterator but it turns out I have to assign it to a variable for it to work. I don't understand the compiler error. What's the difference?

Upvotes: 4

Views: 1200

Answers (2)

Karl Nicoll
Karl Nicoll

Reputation: 16419

The problem is actually on the line above.

for (auto it2 = *it->begin(); it2 != *it->end(); ++it2) {

The type of auto actually translates to char because you're dereferencing your iterator too early. *it->begin() actually takes string.begin() and dereferences it, returning a char. To fix, simply remove the iterator dereference from your for statement, like this:

for (auto it2 = it->begin(); it2 != it->end(); ++it2) {

Upvotes: 4

Paul Evans
Paul Evans

Reputation: 27567

You mixing dereference * together with pointer member ->, use only one:

for (auto it2 = it->begin(); it2 != it->end(); ++it2) {

or

for (auto it2 = (*it).begin(); it2 != (*it).end(); ++it2) {

Upvotes: 1

Related Questions