-3

Thanks for your attention! Errors occur when using "." and the below are my code.

using namespace std;
#include <vector>
#include <iostream>
void main() {
    vector<int> v;
    vector<int>* pv = &v;
    v.push_back(1);
    pv->push_back(2);
    //*pv.push_back(2); //error1

    for (auto it = v.begin(); it != v.end(); it++) { cout << *it << endl; }
    for (auto it = pv->begin(); it != pv->end(); it++) { cout << *it << endl; }
    //for (auto it = *pv.begin(); it != *pv.end(); it++) { cout << *it << endl; } //error2

    cout << typeid(pv->begin()).name() << endl;
    //cout << typeid(*pv.begin()).name() << endl; //error3
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
朱泓润
  • 1
  • 1
  • `pv->x` would be syntactic sugar for `(*pv).x`. – jxh Dec 31 '21 at 09:03
  • 1
    Does this answer your question? [What is the difference between the dot (.) operator and -> in C++?](https://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c) – Ch3steR Dec 31 '21 at 09:04
  • 1
    To answer your question - it is because of operator precedence. `.` has higher precedence than `*`, so you are trying to invoke `push_back` on pointer. – pocza Dec 31 '21 at 09:05
  • BTW, you should be commended for authoring a clear question with a nice MCVE. The downvotes reflect that this is a common question, not a badly asked one. – jxh Dec 31 '21 at 09:07

1 Answers1

1

The unary operator * has a lower precedence than the postfix operator ..

So this statement

*pv.push_back(2);

is equivalent to

*( pv.push_back(2) );

You have to write instead

( *pv ).push_back(2);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335