Namespaces
Variants
Views
Actions

std::data

From cppreference.com
< cpp‎ | iterator
Revision as of 00:08, 15 August 2018 by LittleFlower (Talk | contribs)

 
 
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
data
(C++17)
 
Defined in header <iterator>
template <class C>
constexpr auto data(C& c) -> decltype(c.data());
(1) (since C++17)
template <class C>
constexpr auto data(const C& c) -> decltype(c.data());
(2) (since C++17)
template <class T, std::size_t N>
constexpr T* data(T (&array)[N]) noexcept;
(3) (since C++17)
template <class E>
constexpr const E* data(std::initializer_list<E> il) noexcept;
(4) (since C++17)

Returns a pointer to the block of memory containing the elements of the container.

1,2) returns c.data()
3) returns array
4) returns il.begin()

Contents

Parameters

c - a container with a data() method
array - an array of arbitrary type
il - an initializer list

Return value

A pointer to the block of memory containing the elements of the container.

Notes

In addition to being included in <iterator>, std::data is guaranteed to become available if any of the following headers are included: <array>, <deque>, <forward_list>, <list>, <map>, <regex>, <set>, <span>(since C++20), <string>, <string_view>, <unordered_map>, <unordered_set>, and <vector>.

Possible implementation

First version
template <class C> 
constexpr auto data(C& c) -> decltype(c.data())
{
    return c.data();
}
Second version
template <class C> 
constexpr auto data(const C& c) -> decltype(c.data())
{
    return c.data();
}
Third version
template <class T, std::size_t N>
constexpr T* data(T (&array)[N]) noexcept
{
    return array;
}
Fourth version
template <class E> 
constexpr const E* data(std::initializer_list<E> il) noexcept
{
    return il.begin();
}

Example

#include <string> //std::data is guaranteed to be available after inclusion
#include <cstring>
#include <iostream>
 
int main()
{
    std::string s {"Hello world!\n"};
 
    char a[20]; //a C-style string
    std::strcpy(a, std::data(s)); //s.data() is guaranteed to be a NBTS sinc C++11
 
    std::cout << a << "\n";
}

Output:

Hello world!