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 ( ) .

目次

翻訳内容: - "Contents" → "目次" - その他のC++関連用語(Parameters, Return value, Exceptions, Notes, Possible implementation, Example, See also)は翻訳せずに保持 - HTMLタグ、属性、クラス名、ID、リンク先はすべて保持 - 番号部分は変更なし

パラメータ

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() , および 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));
//  [s.data(), s.data() + s.size()] は C++11 以降 NTBS であることが保証されています
    std::cout << a;
}

出力:

Hello world!

関連項目

連続範囲の先頭へのポインタを取得する
(カスタマイゼーションポイントオブジェクト)
読み取り専用連続範囲の先頭へのポインタを取得する
(カスタマイゼーションポイントオブジェクト)