Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it portable to treat std::vector like array [duplicate]

I have seen people in my team writing code like this. I personally think this is not portable since vector could be implemented in a totally different way. Am I right?

vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);

int* b = &a[0];
std::cout<< *(b +1); // this will print 2
like image 686
PeacefulPanda Avatar asked Nov 01 '13 13:11

PeacefulPanda


People also ask

Can I treat a vector like an array C++?

Yes, that's fine. As of C++03, vector is required to have contiguous storage. As of C++11, the same is true for std::string , by the way; and you can say v. data() as a synonym for &v[0] (which is also valid when v is empty).

Is std::vector slower than array?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

Which is faster std :: array or std::vector?

The conclusion is that arrays of integers are faster than vectors of integers (5 times in my example). However, arrays and vectors are arround the same speed for more complex / not aligned data.

Should I use std::vector or std array?

Okay, I can make it short today. Here is a rule of thumb: If you want to add elements to your container or remove elements from your container, use a std::vector; if not, use a std::array.


1 Answers

That code is correct. The elements stored in a std::vector are guaranteed to be stored contiguously as of C++03.

This is the relevant part of the current standard C++ draft N3797 (23.3.6.1):

A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

like image 65
mfontanini Avatar answered Oct 18 '22 13:10

mfontanini