std::set begin() 方法
- 自 C++11 起
- 直到 C++11
// Non const version
iterator begin() noexcept;
// Const version
iterator begin() const noexcept;
// Const version
const_iterator cbegin() const noexcept;
// Non const version
iterator begin();
// Const version
const_iterator cbegin();
返回指向数组末尾之后元素的迭代器。
指向 set 的第一个元素。如果 set 为空,返回的迭代器将等于end()
。
参数
(无)
返回值
指向第一个元素的迭代器。
异常
(无)
复杂度
常数 - O(1)。
begin 和 cbegin 的区别
对于 const 容器 c
,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- begin
- cbegin
#include <set>
int main()
{
std::set<int> set = {1, 2, 3, 4, 5};
auto it = set.begin(); // Type: std::set<int>::iterator
*it = 5; // ✔ Ok
}
#include <set>
int main()
{
std::set<int> set = {1, 2, 3, 4, 5};
auto it = set.cbegin(); // Type: std::set<int>::const_iterator
*it = 5; // ❌ Error!
}
- begin
- cbegin
#include <set>
int main()
{
const std::set<int> set = {1, 2, 3, 4, 5};
auto it = set.begin(); // Type: std::set<int>::const_iterator
*it = 5; // ❌ Error!
}
#include <set>
int main()
{
const std::set<int> set = {1, 2, 3, 4, 5};
auto it = set.cbegin(); // Type: std::set<int>::const_iterator
*it = 5; // ❌ Error!
}
示例
Main.cpp
#include <algorithm>
#include <iostream>
#include <set>
int main() {
std::set<int> set = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
std::for_each(set.cbegin(), set.cend(), [](int x) {
std::cout << x << ' ';
});
std::cout << '\n';
}
输出
1 2 3 4 5 6 9