跳到主要内容

std::unordered_set begin() 方法

// 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的容器,它们返回不同的迭代器

#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
}

示例

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)
本文来源于此 CppReference 页面。它可能为了改进或编辑偏好而有所改动。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::unordered_set begin() 方法

// 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的容器,它们返回不同的迭代器

#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
}

示例

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)
本文来源于此 CppReference 页面。它可能为了改进或编辑偏好而有所改动。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。