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?
it->begin()is thestring's iterator.*it->begin()dereferences that to give you achar.