跳到主要内容

std::map begin() 方法

// Non const version
iterator begin() noexcept;

// Const version
iterator begin() const noexcept;

// Const version
const_iterator cbegin() const noexcept;

返回指向数组末尾之后元素的迭代器

指向 map 的第一个元素。如果数组为空,返回的迭代器将等于 end()

参数

(无)

返回值

指向第一个元素的迭代器。

异常

(无)

复杂度

常数 - O(1)

begin 和 cbegin 的区别

对于 const 容器 c,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()

对于非常量类型c的容器,它们返回不同的迭代器

#include <map>

int main()
{
std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = map.begin(); // Type: std::map<int, float>::iterator
*it = 5; // ✔ Ok
}

示例

Main.cpp
#include <iostream>
#include <map>

int main() {
std::map<int, float> num_map;
num_map[4] = 4.13;
num_map[9] = 9.24;
num_map[1] = 1.09;
// calls a_map.begin() and a_map.end()
for (auto it = num_map.begin(); it != num_map.end(); ++it) {
std::cout << it->first << ", " << it->second << '\n';
}
}
输出
1, 1.09
4, 4.13
9, 9.24
本文源自此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。

std::map begin() 方法

// Non const version
iterator begin() noexcept;

// Const version
iterator begin() const noexcept;

// Const version
const_iterator cbegin() const noexcept;

返回指向数组末尾之后元素的迭代器

指向 map 的第一个元素。如果数组为空,返回的迭代器将等于 end()

参数

(无)

返回值

指向第一个元素的迭代器。

异常

(无)

复杂度

常数 - O(1)

begin 和 cbegin 的区别

对于 const 容器 c,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()

对于非常量类型c的容器,它们返回不同的迭代器

#include <map>

int main()
{
std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = map.begin(); // Type: std::map<int, float>::iterator
*it = 5; // ✔ Ok
}

示例

Main.cpp
#include <iostream>
#include <map>

int main() {
std::map<int, float> num_map;
num_map[4] = 4.13;
num_map[9] = 9.24;
num_map[1] = 1.09;
// calls a_map.begin() and a_map.end()
for (auto it = num_map.begin(); it != num_map.end(); ++it) {
std::cout << it->first << ", " << it->second << '\n';
}
}
输出
1, 1.09
4, 4.13
9, 9.24
本文源自此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。