Reputation: 53
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
Upvotes: 5
Views: 3402
Reputation: 491
std::vector
is a sequence container that encapsulates dynamic size arrays.
So definately, it is not a pointer.
As @tadman said, v
(an instance of the vector class) does happen to contain a pointer to the start of the array.
You cannot access *v
because there is no overload for the unary operator* for the class std::vector
.
Upvotes: 1
Reputation:
No the vector in c++ is not a pointer. The vector is a class in c++
Upvotes: 0
Reputation: 238361
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
.
Upvotes: 11
Reputation: 211610
The std::vector
structure may contain additional data, such as the length. The contiguous elements are stored in a separate location and that location changes as the array is resized. &v
should remain the same so long as v
isn't moved, but &v[0]
can be invalidated for a number of reasons.
Imagine, in very rough terms, it's:
struct vector {
size_t size;
T* elements;
};
The operator[]
implementation takes over when you employ &v[0]
.
It's not a pointer, and it behaves very differently from new[]
.
Upvotes: 4