std::ranges::ends_with
来自cppreference.com
| 在标头 <algorithm> 定义
|
||
| 调用签名 |
||
| |
(1) | (C++23 起) |
| (2) | (C++23 起) | |
检查第二范围是否匹配第一范围的后缀。
1) 设
N1 为 ranges::distance(first1, last1),N2 为 ranges::distance(first2, last2):
- 如果
N1 < N2是true,那么返回false。 - 否则返回
ranges::equal(std::move(first1) + (N1 - N2), last1,std::move(first2), last2, pred, proj1, proj2)。
2) 设
N1 为 ranges::distance(r1),N2 为 ranges::distance(r2):
- 如果
N1 < N2是true,那么返回false。 - 否则返回
ranges::equal(views::drop(ranges::ref_view(r1),N1 - static_cast<decltype(N1)>(N2)),r2, pred, proj1, proj2)。
此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:
参数
| first1, last1 | - | 要检验的元素范围的迭代器-哨位对 |
| r1 | - | 要检验的元素范围 |
| first2, last2 | - | 要用作后缀的元素范围的迭代器-哨位对 |
| r2 | - | 要用作后缀的元素范围 |
| pred | - | 比较投影后元素的二元谓词 |
| proj1 | - | 应用到要检验的元素范围的投影 |
| proj2 | - | 应用到要用作后缀的元素范围的投影 |
返回值
在第二范围匹配第一范围的后缀时返回 true,否则返回 false。
复杂度
通常是线性:至多应用 min(N1,N2) 次谓词和两个投影。在 N1 < N2 是 true 时不会应用谓词和两个投影。
如果 N1 与 N2 都能以常数时间计算(即两个迭代器-哨位类型对均实现 sized_sentinel_for,或两个范围类型都实现了 sized_range)且 N1 < N2 是 true,那么时间复杂度是常数。
可能的实现
|
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_ranges_starts_ends_with |
202106L |
(C++23) | std::ranges::starts_with, std::ranges::ends_with
|
示例
运行此代码
#include <algorithm>
#include <array>
static_assert
(
! std::ranges::ends_with("for", "cast") &&
std::ranges::ends_with("dynamic_cast", "cast") &&
! std::ranges::ends_with("as_const", "cast") &&
std::ranges::ends_with("bit_cast", "cast") &&
! std::ranges::ends_with("to_underlying", "cast") &&
std::ranges::ends_with(std::array{1, 2, 3, 4}, std::array{3, 4}) &&
! std::ranges::ends_with(std::array{1, 2, 3, 4}, std::array{4, 5})
);
int main() {}
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 4105 | C++23 | 重载 (2) 通过 N1 - N2[1] 计算两个范围大小的差
|
改成 N1 - static_cast<decltype(N1)>(N2)
|
参阅
(C++23) |
检查一个范围是否始于另一范围 (算法函数对象) |
(C++20) |
检查字符串是否终于给定后缀 ( std::basic_string<CharT,Traits,Allocator> 的公开成员函数) |
(C++20) |
检查字符串视图是否终于给定后缀 ( std::basic_string_view<CharT,Traits> 的公开成员函数) |