std::ranges::empty - cppreference.com

From cppreference.com

Defined in header

<ranges>

Defined in header

<iterator>

inlinenamespace/*unspecified*/{inlineconstexprautoempty=/*unspecified*/;}(since C++20)
(customization point object)Call signature

template<classT>requires/* see below */constexprboolempty(T&&t);(since C++20)Determines whether or not t has any elements.

A call to ranges::empty is

expression-equivalent

to:

bool(t.empty()), if that expression is valid.

Otherwise, (ranges::size(t)==0), if that expression is valid.

Otherwise, bool(ranges::begin(t)==ranges::end(t)), if that expression is valid and decltype(ranges::begin(t)) models

std::forward_iterator

.

In all other cases, a call to ranges::empty is ill-formed, which can result in

substitution failure

when ranges::empty(t) appears in the immediate context of a template instantiation.

Customization point objects

The name ranges::empty denotes a customization point object, which is a const

function object

of a

literal

semiregular

class type. See

CustomizationPointObject

for details.

Example

Run this code

#include<iostream>#include<ranges>#include<vector>template<std::ranges::input_rangeR>voidprint(charid,R&&r){if(std::ranges::empty(r)){std::cout<<'\t'<<id<<") Empty\n";return;}std::cout<<'\t'<<id<<") Elements:";for(constauto&element:r)std::cout<<' '<<element;std::cout<<'\n';}intmain(){{autov=std::vector<int>{1,2,3};std::cout<<"(1) ranges::empty uses std::vector::empty:\n";print('a',v);v.clear();print('b',v);}{std::cout<<"(2) ranges::empty uses ranges::size(initializer_list):\n";autoil={7,8,9};print('a',il);print('b',std::initializer_list<int>{});}{std::cout<<"(2) ranges::empty on a raw array uses ranges::size:\n";intarray[]={4,5,6};// array has a known boundprint('a',array);}{structScanty:privatestd::vector<int>{usingstd::vector<int>::begin;usingstd::vector<int>::end;usingstd::vector<int>::push_back;// Note: both empty() and size() are hidden};std::cout<<"(3) calling ranges::empty on an object w/o empty() or size():\n";Scantyy;print('a',y);y.push_back(42);print('b',y);}}Output:

(1) ranges::empty uses std::vector::empty: a) Elements: 1 2 3 b) Empty (2) ranges::empty uses ranges::size(initializer_list): a) Elements: 7 8 9 b) Empty (2) ranges::empty on a raw array uses ranges::size: a) Elements: 4 5 6 (3) calling ranges::empty on an object w/o empty() or size(): a) Empty b) Elements: 42 See also

(C++17)

checks whether the container is empty
(function template)

[edit]