std::map<Key,T,Compare,Allocator>:: end, std::map<Key,T,Compare,Allocator>:: cend
From cppreference.net
|
iterator end
(
)
;
|
(1) |
(自 C++11 起为 noexcept)
(自 C++26 起为 constexpr) |
|
const_iterator end
(
)
const
;
|
(2) |
(自 C++11 起为 noexcept)
(自 C++26 起为 constexpr) |
|
const_iterator cend
(
)
const
noexcept
;
|
(3) |
(自 C++11 起)
(自 C++26 起为 constexpr) |
返回指向 * this 最后一个元素之后位置的迭代器。
此返回的迭代器仅作为哨兵使用。不保证其具有 可解引用性 。
目录 |
返回值
指向最后一个元素之后的迭代器。
复杂度
常量。
注释
libc++ 向后移植
cend()
至 C++98 模式。
示例
运行此代码
输出:
1, 1.09 4, 4.13 9, 9.24
使用自定义比较函数的示例
运行此代码
#include <cmath> #include <iostream> #include <map> struct Point { double x, y; }; // 比较两个Point指针的x坐标 struct PointCmp { bool operator()(const Point* lhs, const Point* rhs) const { return lhs->x < rhs->x; } }; int main() { // 注意虽然x坐标是无序的,但map会按x坐标递增顺序迭代 Point points[3] = {{2, 0}, {1, 0}, {3, 0}}; // mag是一个将节点地址映射到其在x-y平面模长的map // 虽然键是指向Point的指针,但我们希望通过点的x坐标而非Point的地址来排序map // 这通过使用PointCmp类的比较方法实现 std::map<Point*, double, PointCmp> mag( {{points, 2}, {points + 1, 1}, {points + 2, 3}} ); // 将每个y坐标从0改为模长值 for (auto iter = mag.begin(); iter != mag.end(); ++iter) { auto cur = iter->first; // 指向Node的指针 cur->y = mag[cur]; // 也可以使用 cur->y = iter->second; } // 更新并打印每个节点的模长 for (auto iter = mag.begin(); iter != mag.end(); ++iter) { auto cur = iter->first; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << iter->second << '\n'; } // 使用基于范围的for循环重复上述操作 for (auto i : mag) { auto cur = i.first; cur->y = i.second; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << mag[cur] << '\n'; // 注意与上面 std::cout << iter->second << '\n'; 对比, // std::cout << i.second << '\n'; 不会打印更新后的模长 // 如果使用 auto &i : mag,则会打印更新后的模长 } }
输出:
The magnitude of (1, 1) is 1.41421 The magnitude of (2, 2) is 2.82843 The magnitude of (3, 3) is 4.24264 The magnitude of (1, 1.41421) is 1.73205 The magnitude of (2, 2.82843) is 3.4641 The magnitude of (3, 4.24264) is 5.19615
参见
|
(C++11)
|
返回指向起始位置的迭代器
(公开成员函数) |
|
(C++11)
(C++14)
|
返回指向容器或数组末尾的迭代器
(函数模板) |