Namespaces
Variants
Views
Actions

std::empty

From cppreference.com
< cpp‎ | iterator
Revision as of 11:49, 31 March 2017 by T. Canens (Talk | contribs)

 
 
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)
empty
(C++17)
(C++17)
 
Defined in header <iterator>
template <class C>
constexpr auto empty(const C& c) -> decltype(c.empty());
(1) (since C++17)
template <class T, std::size_t N>
constexpr bool empty(const T (&array)[N]) noexcept;
(2) (since C++17)
template <class E>
constexpr bool empty(std::initializer_list<E> il) noexcept;
(3) (since C++17)

Returns whether the given container is empty.

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

Contents

Parameters

c - a container with an empty method
array - an array of arbitrary type
il - an initializer list

Return value

true if the container doesn't have any element.

Exceptions

2,3)
noexcept specification:  
noexcept
  

Notes

In addition to being included in <iterator>, std::empty is guaranteed to become available if any of the following headers are included: <array>, <deque>, <forward_list>, <list>, <map>, <regex>, <set>, <span>(since C++20), <string>, <string_view>, <unordered_map>, <unordered_set>, and <vector>.

Possible implementation

First version
template <class C> 
constexpr auto empty(const C& c) -> decltype(c.empty())
{
    return c.empty();
}
Second version
template <class T, std::size_t N> 
constexpr bool empty(const T (&array)[N]) noexcept
{
    return false;
}
Third version
template <class E> 
constexpr bool empty(std::initializer_list<E> il) noexcept
{
    return il.size() == 0;
}

Example

#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);
}

Output:

Elements:
1
2
3
Empty
Elements:
4
5
6
Elements:
7
8
9