Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is vector in c++ a pointer?

So lets say we have a vector v and I pass this to a function f

void f(vector<int> &v) {
    cout<<&v;
}

int main() {
    vector<int> v;
    v.push_back(10);  
    v.push_back(20);
    v.push_back(30);

    cout<<&v[0]<<"\n"<<&v<<"\n";
    f(v);
}

For this I get the outputs as:

0x55c757b81300
0x7ffded6b8c70
0x7ffded6b8c70

We can see that &v and &v[0] have different address. So is v a pointer that points to the start of the vector? If so, why can't I access *v? Is there a mistake I'm making?

Thanks

like image 583
Rishab Balasubramanian Avatar asked Dec 03 '22 17:12

Rishab Balasubramanian


1 Answers

Is vector in c++ a pointer?

No. std::vector is not a pointer. It is a class.

So is v a pointer that points to the start of the vector?

No, but v (an instance of the vector class) does happen to contain a pointer to the start of the array.

why can't I access *v?

Because there is no overload for the unary operator* for the class std::vector.

like image 127
eerorika Avatar answered Dec 18 '22 16:12

eerorika