std::multiset end() 方法
- 自 C++11 起
- 直到 C++11
// Non const version
iterator end() noexcept;
// Const version
iterator end() const noexcept;
// Const version
const_iterator cend() const noexcept;
// Non const version
iterator end();
// Const version
const_iterator cend();
返回指向数组末尾之后元素的迭代器。
指向数组末尾的下一个元素。如果数组为空,返回的迭代器将等于begin()
。
尝试解引用末尾之后的迭代器是未定义行为
.参数
(无)
返回值
指向第一个元素的迭代器。
异常
(无)
复杂度
常数 - O(1)。
end 和 cend 的区别
对于 const 容器 c
,end 和 cend 是相同的 - c.end() == c.cend()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- end
- cend
#include <multiset>
int main()
{
std::multiset<int> multiset = { 1, 2, 3 };
auto it = arr.end(); // Type: std::multiset<int>::iterator
*std::prev(it) = 5; // ✔ Ok
}
#include <multiset>
int main()
{
std::multiset<int> multiset = { 1, 2, 3 };
auto it = arr.cend(); // Type: std::multiset<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
- end
- cend
#include <map>
int main()
{
const std::multiset<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = arr.end(); // Type: std::multiset<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
#include <map>
int main()
{
const std::multiset<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = arr.cend(); // Type: std::multiset<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
示例
Main.cpp
#include <iostream>
#include <iterator>
#include <set>
#include <string>
int main()
{
const std::multiset<std::string> words = {
"some", "not", "sorted", "words",
"will", "come", "out", "sorted",
};
for (auto it = words.begin(); it != words.end(); ) {
auto cnt = words.count(*it);
std::cout << *it << ":\t" << cnt << '\n';
std::advance(it, cnt); // all cnt elements have equivalent keys
}
}
输出
come: 1
not: 1
out: 1
some: 1
sorted: 2
will: 1
words: 1