CppDS.com

C++ 98 11 14 17 20 手册

std::unordered_set<Key,Hash,KeyEqual,Allocator>::begin, std::unordered_set<Key,Hash,KeyEqual,Allocator>::cbegin

来自cppreference.com

 
 
 
 
iterator begin() noexcept;
(C++11 起)
const_iterator begin() const noexcept;
(C++11 起)
const_iterator cbegin() const noexcept;
(C++11 起)

返回指向 unordered_set 首元素的迭代器。

unordered_set 为空,则返回的迭代器将等于 end()

range-begin-end.svg

参数

(无)

返回值

指向首元素的迭代器。

复杂度

常数。

注意

因为 iteratorconst_iterator 都是常迭代器(而且实际上可以是同一类型),故不可能通过任何这些成员函数返回的迭代器修改容器元素。

示例

#include <iostream>
#include <unordered_set>
 
struct Point { double x, y; };
 
int main() {
    Point pts[3] = { {1, 0}, {2, 0}, {3, 0} };
 
    // points 是含有点的地址的 set
    std::unordered_set<Point *> points = { pts, pts + 1, pts + 2 };
 
    // 更改每个 (i, 0) 的 y 坐标从 0 到 i^2 并打印点
    for(auto iter = points.begin(); iter != points.end(); ++iter){
        (*iter)->y = ((*iter)->x) * ((*iter)->x); // iter 为指向 Point* 的指针
        std::cout << "(" << (*iter)->x << ", " << (*iter)->y << ") ";
    }
    std::cout << '\n';
 
    // 现在用基于范围的 for 循环,我们把每个 y 坐标增加 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)

参阅

返回指向末尾的迭代器
(公开成员函数)
关闭