名前空間
変種
操作

std::empty

From cppreference.com
 
 
イテレータライブラリ
イテレータのコンセプト
イテレータのプリミティブ
アルゴリズムのコンセプトとユーティリティ
間接呼び出し可能コンセプト
共通アルゴリズム要件
(C++20)
(C++20)
(C++20)
ユーティリティ
(C++20)
イテレータアダプタ
Rangeアクセス
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
empty
(C++17)
(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 empty( const C& c ) -> decltype(c.empty());
(1) (C++17以降)
template< class T, std::size_t N >
constexpr bool empty( const T (&array)[N] ) noexcept;
(2) (C++17以降)
template< class E >
constexpr bool empty( std::initializer_list<E> il ) noexcept;
(3) (C++17以降)

与えられた範囲が空であるかどうかを返す。

1) c.empty() を返す。
2) false を返す。
3) il.size() == 0 を返す。

目次

[編集] パラメータ

c - empty メンバ関数を持つコンテナまたはビュー
array - 任意の型の配列
il - std::initializer_list

[編集] 戻り値

1) c.empty()
2) false
3) il.size() == 0

[編集] 例外

1) 実装定義の例外を投げる可能性がある。

[編集] 備考

std::initializer_listempty メンバ関数を持たないため、そのオーバーロードが必要である。

機能テストマクロ 規格 機能
__cpp_lib_nonmember_container_access 201411L (C++17) std::size(), std::data(), および std::empty()

[編集] 可能な実装

最初のバージョン
template<class C>
[[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty())
{
    return c.empty();
}
2番目のバージョン
template<class T, std::size_t N>
[[nodiscard]] constexpr bool empty(const T (&array)[N]) noexcept
{
    return false;
}
第3版
template<class E>
[[nodiscard]] constexpr bool empty(std::initializer_list<E> il) noexcept
{
    return il.size() == 0;
}

[編集]

#include <iostream>
#include <vector>
 
template<class T>
void print(const T& container)
{
    if (std::empty(container))
        std::cout << "Empty\n";
    else
    {
        std::cout << "Elements:";
        for (const auto& element : container)
            std::cout << ' ' << element;
        std::cout << '\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

[編集] 関連項目

rangeが空かどうかをチェックする
(カスタマイゼーションポイントオブジェクト)[編集]
English 日本語 中文(简体) 中文(繁體)