std::vector: vec.data() or &vec[0]

arrays, c++, vector

Solution

`data()` is brand new to C++11, that's why you don't see it as often. The idea of using `&vec.front()` never even occurred to me, probably because I use `operator[]` alot more often than `front()` (almost never). I imagine it's the same for other people.

Problem

When you want access a std::vector as a C array you can choose from at least four different ways, as you can see in this example: ``` #include <iostream> #include <vector> using namespace std; int main() { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(42); vec.push_back(24024); { int* arr = vec.data(); cout << arr << endl; /* output: 0x9bca028 */ cout << arr[3] << endl; /* output : 24024 */ } { int* arr = &vec.front(); cout << arr << endl; /* output: 0x9bca028 */ cout << arr[3] << endl; /* output : 24024 */ } { int* arr = &vec[0]; cout << arr << endl; /* output: 0x9bca028 */ cout << arr[3] << endl; /* output : 24024 */ } { int* arr = &vec.at(0); cout << arr << endl; /* output: 0x9bca028 */ cout << arr[3] << endl; /* output : 24024 */ } } ``` The one I've found in most cases is the `&vec[0]`. I think it's the least elegant, so... why is it the most used? Is it more efficient or more compatible? I can't find lot of documentation about `data()`.

Original source