std::ranges:: empty
|
||||||||||||||||||||||
| Range primitives | |||||||
|
|||||||
| Range concepts | |||||||||||||||||||
|
|||||||||||||||||||
| Range factories | |||||||||
|
|||||||||
| Range adaptors | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||
| Helper items | |||||||||||||||||
|
|
||||||||||||||||
|
定义于头文件
<ranges>
|
||
|
定义于头文件
<iterator>
|
||
|
inline
namespace
/*unspecified*/
{
inline
constexpr
auto
empty
=
/*unspecified*/
;
|
(C++20 起)
(定制点对象) |
|
|
调用签名
|
||
|
template
<
class
T
>
requires
/* 见下文 */
|
(C++20 起) | |
判断 t 是否包含任何元素。
对
ranges::empty
的调用在
表达式等价性
上等同于:
- bool ( t. empty ( ) ) ,若该表达式合法。
- 否则, ( ranges:: size ( t ) == 0 ) ,若该表达式合法。
- 否则, bool ( ranges:: begin ( t ) == ranges:: end ( t ) ) ,若该表达式合法且 decltype ( ranges:: begin ( t ) ) 满足 std::forward_iterator 概念。
在所有其他情况下,对
ranges::empty
的调用都是非良构的,当
ranges
::
empty
(
t
)
出现在模板实例化的直接上下文中时,这可能导致
替换失败
。
定制点对象
名称
ranges::empty
表示一个
定制点对象
,它是一个字面量
semiregular
类类型的常量
函数对象
。详细信息请参阅
定制点对象
。
示例
#include <iostream> #include <ranges> #include <vector> template<std::ranges::input_range R> void print(char id, R&& r) { if (std::ranges::empty(r)) { std::cout << '\t' << id << ") 空\n"; return; } std::cout << '\t' << id << ") 元素:"; for (const auto& element : r) std::cout << ' ' << element; std::cout << '\n'; } int main() { { auto v = std::vector<int>{1, 2, 3}; std::cout << "(1) ranges::empty 使用 std::vector::empty:\n"; print('a', v); v.clear(); print('b', v); } { std::cout << "(2) ranges::empty 使用 ranges::size(initializer_list):\n"; auto il = {7, 8, 9}; print('a', il); print('b', std::initializer_list<int>{}); } { std::cout << "(2) ranges::empty 在原始数组上使用 ranges::size:\n"; int array[] = {4, 5, 6}; // array has a known bound print('a', array); } { struct Scanty : private std::vector<int> { using std::vector<int>::begin; using std::vector<int>::end; using std::vector<int>::push_back; // Note: both empty() and size() are hidden }; std::cout << "(3) 在无 empty() 或 size() 的对象上调用 ranges::empty:\n"; Scanty y; print('a', y); y.push_back(42); print('b', y); } }
输出:
(1) ranges::empty 使用 std::vector::empty:
a) 元素:1 2 3
b) 空
(2) ranges::empty 使用 ranges::size(initializer_list):
a) 元素:7 8 9
b) 空
(2) ranges::empty 在原始数组上使用 ranges::size:
a) 元素:4 5 6
(3) 在无 empty() 或 size() 的对象上调用 ranges::empty:
a) 空
b) 元素:42
参见
|
(C++17)
|
检查容器是否为空
(函数模板) |