std::data
From cppreference.com
| ヘッダー <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(), および std::empty() |
[編集] 可能な実装
| 最初のバージョン |
|---|
template<class C> constexpr auto data(C& c) -> decltype(c.data()) { return c.data(); } |
| 2番目のバージョン |
template<class C> constexpr auto data(const C& c) -> decltype(c.data()) { return c.data(); } |
| 第3版 |
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]; // storage for a C-style string std::strcpy(a, std::data(s)); // [s.data(), s.data() + s.size()] is guaranteed to be an NTBS since C++11 std::cout << a; }
出力
Hello world!
[編集] 関連項目
| (C++20) |
連続rangeの先頭へのポインタを取得する (カスタマイゼーションポイントオブジェクト) |
| (C++20) |
読み取り専用の連続rangeの先頭へのポインタを取得する (カスタマイゼーションポイントオブジェクト) |