std::unordered_multimap begin()/cbegin() 方法
- 自 C++11 起
// Non const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
// Const version
const_iterator cbegin() const noexcept;
返回指向数组末尾之后元素的迭代器。
到 vector 的第一个元素。如果数组为空,则返回的迭代器将等于end()
。
参数
(无)
返回值
指向第一个元素的迭代器。
复杂度
常数 - O(1)。
begin 和 cbegin 的区别
对于 const 容器 c
,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- begin
- cbegin
#include <unordered_map>
#include <string>
int main()
{
std::unordered_multimap<std::string, int> map = {
{ "key1", 1 },
{ "key2", 2 },
{ "key3", 3 },
};
auto it = map.begin(); // Type: std::unordered_multimap<std::string, int>::iterator
it->second = 5; // ✔ Ok
}
#include <unordered_map>
#include <string>
int main()
{
std::unordered_multimap<std::string, int> map = {
{ "key1", 1 },
{ "key2", 2 },
{ "key3", 3 },
};
auto it = map.cbegin(); // Type: std::unordered_multimap<std::string, int>::const_iterator
it->second = 5; // ❌ Error!
}
- begin
- cbegin
#include <unordered_map>
#include <string>
int main()
{
const std::unordered_multimap<std::string, int> map = {
{ "key1", 1 },
{ "key2", 2 },
{ "key3", 3 },
};
auto it = map.begin(); // Type: std::unordered_multimap<std::string, int>::const_iterator
it->second = 5; // ❌ Error!
}
#include <unordered_map>
#include <string>
int main()
{
const std::unordered_multimap<std::string, int> map = {
{ "key1", 1 },
{ "key2", 2 },
{ "key3", 3 },
};
auto it = map.cbegin(); // Type: std::unordered_multimap<std::string, int>::const_iterator
it->second = 5; // ❌ Error!
}
示例
Main.cpp
#include <unordered_map>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <string>
#include <utility>
int main()
{
auto show_node = [](const std::pair<std::string, std::string>& node) {
std::cout << node.first << " : " << node.second << '\n';
};
std::unordered_multimap<std::string, std::string> lemmas;
assert(lemmas.begin() == lemmas.end()); // OK
assert(lemmas.cbegin() == lemmas.cend()); // OK
lemmas.insert({ "1. ∀x ∈ N ∃y ∈ N", "x ≤ y" });
show_node(*lemmas.cbegin());
assert(lemmas.begin() != lemmas.end()); // OK
assert(lemmas.cbegin() != lemmas.cend()); // OK
lemmas.begin()->second = "x < y";
show_node(*lemmas.cbegin());
lemmas.insert({ "2. ∀x,y ∈ N", "x = y V x ≠ y" });
show_node(*lemmas.cbegin());
lemmas.insert({ "3. ∀x ∈ N ∃y ∈ N", "y = x + 1" });
show_node(*lemmas.cbegin());
std::cout << "lemmas: \n";
std::for_each(lemmas.cbegin(), lemmas.cend(),
[&](const auto& n) { show_node(n); });
std::cout << "\n";
}
可能的输出
1. ∀x ∈ N ∃y ∈ N : x ≤ y
1. ∀x ∈ N ∃y ∈ N : x < y
2. ∀x,y ∈ N : x = y V x ≠ y
3. ∀x ∈ N ∃y ∈ N : y = x + 1
lemmas:
3. ∀x ∈ N ∃y ∈ N : y = x + 1
1. ∀x ∈ N ∃y ∈ N : x < y
2. ∀x,y ∈ N : x = y V x ≠ y