Namespaces
Variants

std:: data

From cppreference.net
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)
定义于头文件 <array>
定义于头文件 <deque>
定义于头文件 <flat_map>
定义于头文件 <flat_set>
定义于头文件 <forward_list>
定义于头文件 <inplace_vector>
定义于头文件 <iterator>
定义于头文件 <list>
定义于头文件 <map>
定义于头文件 <regex>
定义于头文件 <set>
定义于头文件 <span>
定义于头文件 <string>
定义于头文件 <string_view>
定义于头文件 <unordered_map>
定义于头文件 <unordered_set>
定义于头文件 <vector>
template < class C >
constexpr auto data ( C & c ) - > decltype ( c. data ( ) ) ;
(1) (C++17 起)
template < class C >
constexpr auto data ( const C & c ) - > decltype ( c. data ( ) ) ;
(2) (C++17 起)
template < class T, std:: size_t N >
constexpr T * data ( T ( & array ) [ N ] ) noexcept ;
(3) (C++17 起)
template < class E >
constexpr const E * data ( std:: initializer_list < E > il ) noexcept ;
(4) (C++17 起)

返回指向包含该范围元素的内存块的指针。

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

目录

参数

c - 具有 data ( ) 成员函数的容器或视图
array - 任意类型的数组
il - 一个 std::initializer_list

返回值

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

异常

1) 可能抛出实现定义的异常。

注释

针对 std::initializer_list 的重载是必需的,因为它没有名为 data 的成员函数。

功能测试 标准 功能
__cpp_lib_nonmember_container_access 201411L (C++17) std::size() , std::data() , and std::empty()

可能的实现

第一版本
template<class C>
constexpr auto data(C& c) -> decltype(c.data())
{
    return c.data();
}
第二版本
template<class C>
constexpr auto data(const C& c) -> decltype(c.data())
{
    return c.data();
}
第三版本
template<class T, std::size_t N>
constexpr T* data(T (&array)[N]) noexcept
{
    return array;
}
第四版本
template<class E>
constexpr const E* data(std::initializer_list<E> il) noexcept
{
    return il.begin();
}

示例

#include <cstring>
#include <iostream>
#include <string>
int main()
{
    std::string s{"Hello world!\n"};
    char a[20]; // 用于存储C风格字符串的空间
    std::strcpy(a, std::data(s));
// 自C++11起,[s.data(), s.data() + s.size()] 保证是一个空终止字节序列
    std::cout << a;
}

输出:

Hello world!

参见

获取连续范围起始位置的指针
(定制点对象)
获取只读连续范围起始位置的指针
(定制点对象)