public member function
<vector>

std::vector::data

      value_type* data() noexcept;
const value_type* data() const noexcept;
Access data
Returns a direct pointer to the memory array used internally by the vector to store its owned elements.

Because elements in the vector are guaranteed to be stored in contiguous storage locations in the same order as represented by the vector, the pointer retrieved can be offset to access any element in the array.

Parameters

none

Return value

A pointer to the first element in the array used internally by the vector.

If the vector object is const-qualified, the function returns a pointer to const value_type. Otherwise, it returns a pointer to value_type.

Member type value_type is the type of the elements in the container, defined in vector as an alias of the first class template parameter (T).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// vector::data
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);

  int* p = myvector.data();

  *p = 10;
  ++p;
  *p = 20;
  p[2] = 100;

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}


Output:
myvector contains: 10 20 0 100 0

Complexity

Constant.

Iterator validity

No changes.

Data races

The container is accessed (neither the const nor the non-const versions modify the container).
No contained elements are directly accessed by the call, but the pointer returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.

Exception safety

No-throw guarantee: this member function never throws exceptions.

See also