std::end, std::cend_C++中文网
| 定义于头文件 |
||
| (1) | ||
| template< class C > |
(C++11 起) (C++17 前) |
|
| template< class C > |
(C++17 起) | |
| (1) | ||
| template< class C > |
(C++11 起) (C++17 前) |
|
| template< class C > |
(C++17 起) | |
| (2) | ||
| template< class T, std::size_t N > |
(C++11 起) (C++14 前) |
|
| template< class T, std::size_t N > |
(C++14 起) | |
| template< class C > constexpr auto cend( const C& c ) noexcept(/* see below */) |
(3) | (C++14 起) |
返回指向给定容器 c 或数组 array 结尾(即最末元素的后一元素)的迭代器。这些模板依赖于拥有合理实现的 C::end() 。
1) 准确返回 c.end() ,典型地是指向 c 所代表的序列末尾后一位置的迭代器。若 C 是标准容器 (Container) ,则在 c 非 const 限定时返回 C::iterator ,否则返回 C::const_iterator 。
2) 返回指向数组 array 末尾的指针。
3) 准确返回 std::end(c) ,这里 c 始终当做 const 限定。若 C 是标准容器 (Container) ,则始终返回 C::const_iterator 。
参数
| c | - | 拥有 end 方法的容器
|
| array | - | 任意类型的数组 |
返回值
指向 c 或 array 结尾的迭代器。注意容器或数组的结尾定义为最后一个合法元素的下一个元素。
异常
3)
注意
除了包含于 <iterator> ,若包含下列任一头文件,则保证 std::end 与 std::cend 可用: <array> 、 <deque> 、 <forward_list> 、 <list> 、 <map> 、 <regex> 、 <set> 、 <span> (C++20 起) 、 <string> 、 <string_view> (C++17 起) 、 <unordered_map> 、 <unordered_set> 及 <vector> 。
用户定义重载
可为不暴露适合的 end() 成员函数的类提供 end 的自定义重载。标准库已提供下列重载:
类似 swap 的使用(描述于可交换 (Swappable) ), end 函数在泛型语境中的典型使用等价于 using std::end; end(arg); ,这允许 ADL 为用户定义类型所选择的重载,和出现于同一重载集中的标准库函数模板。
template<typename Container, typename Function> void for_each(Container&& cont, Function f) { using std::begin; auto it = begin(cont); using std::end; auto end_it = end(cont); while (it != end_it) { f(*it); ++it; } }
示例
#include <iostream> #include <vector> #include <iterator> #include <algorithm> int main() { std::vector<int> v = { 3, 1, 4 }; if (std::find(std::begin(v), std::end(v), 5) != std::end(v)) { std::cout << "found a 5 in vector v!\n"; } int a[] = { 5, 10, 15 }; if (std::find(std::begin(a), std::end(a), 5) != std::end(a)) { std::cout << "found a 5 in array a!\n"; } }
输出: