std::data
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <iterator> で定義
|
||
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 | - | 初期化子リスト |
戻り値
コンテナの要素を格納しているメモリブロックを指すポインタ。
ノート
<iterator> がインクルードされた場合に加えて <array>、 <deque>、 <forward_list>、 <list>、 <map>、 <regex>、 <set>、 <span> (C++20以上)、 <string>、 <string_view>、 <unordered_map>、 <unordered_set>、 <vector> のいずれかのヘッダがインクルードされた場合も、 std::data が利用可能になることが保証されています。
実装例
| 1つめのバージョン |
|---|
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;
}
|
| 4つめのバージョン |
template <class E>
constexpr const E* data(std::initializer_list<E> il) noexcept
{
return il.begin();
}
|
例
Run this code
#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]; //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 << "\n";
}
出力:
Hello world!