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
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).
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.
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.
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.
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 all0 <= n < v.size()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With