std::unordered_set begin() 方法
- 自 C++11 起
// Non const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
// Const version
const_iterator cbegin() const noexcept;
返回指向数组末尾之后元素的迭代器。
指向 `unordered_set` 的第一个元素。如果数组为空,返回的迭代器将等于 `end()`。参数
(无)
返回值
指向第一个元素的迭代器。
异常
(无)
复杂度
常数 - O(1)。
begin 和 cbegin 的区别
对于 const 容器 c
,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- begin
- cbegin
#include <unordered_set>
int main()
{
std::unordered_set<int> unordered_set = {1, 2, 3, 4, 5};
auto it = unordered_set.begin(); // Type: std::unordered_set<int>::iterator
*it = 5; // ✔ Ok
}
#include <unordered_set>
int main()
{
std::unordered_set<int> unordered_set = {1, 2, 3, 4, 5};
auto it = unordered_set.cbegin(); // Type: std::unordered_set<int>::const_iterator
*it = 5; // ❌ Error!
}
- begin
- cbegin
#include <unordered_set>
int main()
{
const std::unordered_set<int> unordered_set = {1, 2, 3, 4, 5};
auto it = unordered_set.begin(); // Type: std::unordered_set<int>::const_iterator
*it = 5; // ❌ Error!
}
#include <unordered_set>
int main()
{
const std::unordered_set<int> unordered_set = {1, 2, 3, 4, 5};
auto it = unordered_set.cbegin(); // Type: std::unordered_set<int>::const_iterator
*it = 5; // ❌ Error!
}
示例
Main.cpp
#include <iostream>
#include <unordered_set>
struct Point { double x, y; };
int main() {
Point pts[3] = { {1, 0}, {2, 0}, {3, 0} };
//points is a set containing the addresses of points
std::unordered_set<Point *> points = { pts, pts + 1, pts + 2 };
//Change each y-coordinate of (i, 0) from 0 into i^2 and print the point
for(auto iter = points.begin(); iter != points.end(); ++iter){
(*iter)->y = ((*iter)->x) * ((*iter)->x); //iter is a pointer-to-Point*
std::cout << "(" << (*iter)->x << ", " << (*iter)->y << ") ";
}
std::cout << '\n';
//Now using the range-based for loop, we increase each y-coordinate by 10
for(Point * i : points) {
i->y += 10;
std::cout << "(" << i->x << ", " << i->y << ") ";
}
}
可能输出
(3, 9) (1, 1) (2, 4)
(3, 19) (1, 11) (2, 14)