-1

The following generates error:

int main() {

  mat_int mat1(5, vector<int>{1,2,3});
  mat_int mat2(5, vector<int>{4,5,6});

  for (auto it1 = mat1.begin(); it1 != mat1.end() ; ++it1) {
        for (auto it11 =  *it1.begin(); it11 != *it1.end(); it11++)
            cout << *it11;
        cout << '\n';
    }
}

Compiler doesn't accept the inner loop iterators; /home/asabbah/programming/C++/vectors1.cpp:16:28: error: ‘class __gnu_cxx::__normal_iterator*, std::vector > >’ has no member named ‘begin’

However, if I insert a temp variable:

vector<int> temp = *it1;

then:

for (auto it11 = temp.begin(); it11 != temp.end(); it11++);

everything goes fine.

Any idea why is this so?

asabbah
  • 55
  • 1
  • 7
  • 1
    It's an [*operator precedence*](http://en.cppreference.com/w/cpp/language/operator_precedence) problem. Try e.g. `it1->begin()` instead, or `(*it1).begin()`. – Some programmer dude Nov 03 '17 at 16:43
  • [`using namespace std;` is a bad practice](https://stackoverflow.com/q/1452721/2176813), never use it. – tambre Nov 03 '17 at 16:47

1 Answers1

5

It's because the member access operator . has a higher priority than the dereference operator *. So it tries to access the begin() method in it1 (which doesn't exist), and then attempts to dereference the result.

Instead of

auto it11 =  *it1.begin();

do

auto it11 =  it1->begin();

Which does what you're intending to do in one step.

Using the temporary variable makes the compiler do the dereference first, and then tries to access the begin method in your temporary variable.

Steve
  • 1,747
  • 10
  • 18