4

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?

1
  • 1
    it->begin() is the string's iterator. *it->begin() dereferences that to give you a char.
    – T.C.
    Commented Jul 11, 2014 at 17:05

2 Answers 2

4

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) {
4
  • 3
    And of course, since he's using auto, he has C++11, and can use for ( std::string line: lines ) { for ( char ch: line ) { ... } } Commented Jul 11, 2014 at 17:09
  • @James Kanze yes I did it before. But the exercise in the book I'm reading is to try it using iterators :) Commented Jul 11, 2014 at 17:14
  • @user3263252 Out of curiosity, which book is it? Commented Jul 11, 2014 at 17:15
  • @Joseph Mansfield c++ primer fifth edition part of Exercise 3.22. I reread the part about arrow operators to check if there's an error in the book just now, and for some reason completely missed the missing "*" in the "->" example! Tsk! Commented Jul 11, 2014 at 17:22
1

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) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.