Reputation: 35
I know that using raw pointers on vectors is not the best way because of the smart ones, but mine is just a question to understand something that I can't wrap my head around... If a I create a vector and then a pointer to it:
vector<int> vec = {1,2,3,4,5};
vector<int> *ptr = &vec;
&
whereas an array doesn't need it?? (aren't vectors dynamic arrays)cout<<*ptr<<endl;
, compiler gives error and I have to write cout<<(*ptr)[1]<<endl;
or cout<< ptr->at(1)
??Usually if you create a pointer to an array that pointer points to the first element.
Can you help me understand what kind of animal vectors are?
Upvotes: 0
Views: 784
Reputation:
aren't vectors dynamic arrays)
Conceptually yes, implementation wise, no. A vector instance is an object, of type std::vector <sometype>
. If you want to take the address of an object like a vector instance, you need to use the address-of, aka &
, operator. A vector is not the same kind of thing as a c++ array.
Why if i write
cout<<*ptr<<endl;
, compiler gives error
Because std::vector doesn't support streaming via operator<<.
Edit:
If you actually wanted to access the internal array, you would do:
vector <int> v = // whatever
int * ip = &v[0];
or:
int * ip = v.data();
Upvotes: 1
Reputation: 43234
Why do i need to use the reference operator(&) whereas an array doesn't need it??(aren't vectors dynamic arrays)
The equivalent of what you've done, with arrays is this:
int array[] = {1,2,3,4,5};
int (*ptr)[5] = &array; // less constrained to just 5 elements with vectors
So yea you still need the &
operator;
Why if i write
cout<<*ptr<<endl;
, compiler gives error and I have to writecout<<(*ptr)[1]<<endl;
orcout<< ptr->at(1)
??
Because vectors are objects and the *
operator was not overloaded to return anything useful apart from the vector itself.
What you probably want to do is to use the std::vector::data
function of vectors which gives you a pointer to the underlying array used by the vector.
Upvotes: 2