std::forward_list end() 方法
- 自 C++11 起
// Non-const version
iterator end() noexcept;
// Const version
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
返回指向数组末尾之后元素的迭代器。
指向数组末尾之后元素的迭代器。注意
如果列表为空,返回的迭代器将等于 begin()
。
未定义行为
尝试解引用末尾之后的迭代器是未定义行为
.参数
(无)
返回值
指向第一个元素的迭代器。
复杂度
常量 - **O(1)*8。
备注
对于容器c
,表达式*c.begin()
等效于c.front()
。
end 和 cend 的区别
对于 const 容器 c
,end
和 cend
是相同的 - c.end() == c.cend()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- end
- cend
#include <forward_list>
int main()
{
std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.end(); // Type: std::forward_list<int>::iterator
*std::prev(it) = 5; // ✔ Ok
}
#include <forward_list>
int main()
{
std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.cend(); // Type: std::forward_list<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
- end
- cend
#include <forward_list>
int main()
{
const std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.end(); // Type: std::forward_list<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
#include <forward_list>
int main()
{
const std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.cend(); // Type: std::forward_list<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
示例
Main.cpp
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <forward_list>
int main()
{
std::forward_list<int> nums {1, 2, 4, 8, 16};
std::forward_list<std::string> fruits {"orange", "apple", "raspberry"};
std::forward_list<char> empty;
// Print forward_list.
std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the forward_list nums (if any), printing only the result.
std::cout << "Sum of nums: "
<< std::accumulate(nums.begin(), nums.end(), 0) << '\n';
// Prints the first fruit in the forward_list fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.begin() << '\n';
if (empty.begin() == empty.end())
std::cout << "forward_list 'empty' is indeed empty.\n";
}
输出
1 2 4 8 16
Sum of nums: 31
First fruit: orange
forward_list 'empty' is indeed empty.