C++ Vector Library - data() Function



Description

The C++ function std::vector::data() returns a pointer to the first element of the vector container.

Declaration

Following is the declaration for std::vector::data() function form std::vector header.

C++11

value_type* data() noexcept;
const value_type* data() const noexcept;

Parameters

None

Return value

Returns constant pointer if vector object is constant qualified otherwise non-constant pointer.

Exceptions

This member function never throws exception.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::vector::data() function.

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};
   int *p;

   p = v.data();

   for (int i = 0; i < v.size(); ++i)
      cout << *p++ << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

1
2
3
4
5
vector.htm
Advertisements