Skip to main content

std::vector data() method

// Non-const version
constexpr T* data() noexcept;

// Const version
constexpr T const* data() const noexcept;

Returns pointer to the underlying array serving as element storage.

The pointer is such that range [ data(); data() + size() ) is always a valid range, even if the container is empty.

Undefined Behaviour

If the container is empty, dereferencing the pointer returned by data() is undefined behavior

.

Parameters

(none)

Return value

Pointer to the underlying element storage.
For a non-empty container c, the returned pointer compares equal to the address of the first element - c.data() == &c[0];

Complexity

Constant - O(1)**.

Notes

If the container is empty, data() may or may not return a null pointer.

Example

Main.cpp
#include <array>
#include <iostream>

int main()
{
std::vector<char> letters {'a', 'b', 'c', 'd', 'e', 'f'};

if (!letters.empty()) {
std::cout << "The last character is '" << letters.back() << "'.\n";
}
}
Output
The last character is 'f'.
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::vector data() method

// Non-const version
constexpr T* data() noexcept;

// Const version
constexpr T const* data() const noexcept;

Returns pointer to the underlying array serving as element storage.

The pointer is such that range [ data(); data() + size() ) is always a valid range, even if the container is empty.

Undefined Behaviour

If the container is empty, dereferencing the pointer returned by data() is undefined behavior

.

Parameters

(none)

Return value

Pointer to the underlying element storage.
For a non-empty container c, the returned pointer compares equal to the address of the first element - c.data() == &c[0];

Complexity

Constant - O(1)**.

Notes

If the container is empty, data() may or may not return a null pointer.

Example

Main.cpp
#include <array>
#include <iostream>

int main()
{
std::vector<char> letters {'a', 'b', 'c', 'd', 'e', 'f'};

if (!letters.empty()) {
std::cout << "The last character is '" << letters.back() << "'.\n";
}
}
Output
The last character is 'f'.
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.