std::empty
提供: cppreference.com
| ヘッダ <iterator> で定義
|
||
| (1) | ||
| template <class C> constexpr auto empty(const C& c) -> decltype(c.empty()); |
(C++17以上) (C++20未満) |
|
| template <class C> [[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty()); |
(C++20以上) | |
| (2) | ||
| template <class T, std::size_t N> constexpr bool empty(const T (&array)[N]) noexcept; |
(C++17以上) (C++20未満) |
|
| template <class T, std::size_t N> [[nodiscard]] constexpr bool empty(const T (&array)[N]) noexcept; |
(C++20以上) | |
| (3) | ||
| template <class E> constexpr bool empty(std::initializer_list<E> il) noexcept; |
(C++17以上) (C++20未満) |
|
| template <class E> [[nodiscard]] constexpr bool empty(std::initializer_list<E> il) noexcept; |
(C++20以上) | |
指定されたコンテナが空かどうかを返します。
1) c.empty() を返します。
2) false を返します。
3) il.size() == 0 を返します。
目次 |
[編集] 引数
| c | - | メンバ関数 empty を持つコンテナ
|
| array | - | 任意の型の配列 |
| il | - | 初期化子リスト |
[編集] 戻り値
コンテナが要素を持っていなければ true。
[編集] ノート
<iterator> がインクルードされた場合に加えて <array>、 <deque>、 <forward_list>、 <list>、 <map>、 <regex>、 <set>、 <span> (C++20以上)、 <string>、 <string_view>、 <unordered_map>、 <unordered_set>、 <vector> のいずれかのヘッダがインクルードされた場合も、 std::empty が利用可能になることが保証されています。
[編集] 実装例
| 1つめのバージョン |
|---|
template <class C> constexpr auto empty(const C& c) -> decltype(c.empty()) { return c.empty(); } |
| 2つめのバージョン |
template <class T, std::size_t N> constexpr bool empty(const T (&array)[N]) noexcept { return false; } |
| 3つめのバージョン |
template <class E> constexpr bool empty(std::initializer_list<E> il) noexcept { return il.size() == 0; } |
[編集] 例
Run this code
#include <iostream> #include <vector> template <class T> void print(const T& container) { if ( !std::empty(container) ) { std::cout << "Elements:\n"; for ( const auto& element : container ) std::cout << element << '\n'; } else { std::cout << "Empty\n"; } } int main() { std::vector<int> c = { 1, 2, 3 }; print(c); c.clear(); print(c); int array[] = { 4, 5, 6 }; print(array); auto il = { 7, 8, 9 }; print(il); }
出力:
Elements: 1 2 3 Empty Elements: 4 5 6 Elements: 7 8 9

