C++ multimap::cend() 函数



C++ 的std::multimap::cend()函数用于返回指向multimap中最后一个元素之后元素的常量迭代器。此迭代器用于只读访问,确保元素不会被修改。它通常与cbegin()一起使用,以只读方式从头到尾迭代multimap。此函数的时间复杂度是常数,即 O(1)。

语法

以下是 std::multimap::cend() 函数的语法。

const_iterator cend() const noexcept;

参数

此函数不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

此函数返回一个指向multimap中最后一个元素的常量迭代器。

示例

让我们来看下面的例子,我们将演示 cend() 函数的使用。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> x = {{1, "Hi"}, {2, "Hello"}, {2, "Namaste"}, {3, "Vanakam"}}; for (auto a = x.cbegin(); a != x.cend(); ++a) { std::cout << a->first << ": " << a->second << std::endl; } return 0; }

输出

以上代码的输出如下:

1: Hi
2: Hello
2: Namaste
3: Vanakam

示例

考虑另一种情况,我们将使用 cend() 函数执行反向迭代。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = {{1, "Tutorix"}, {2, "TP"}, {2, "TutorialsPoint"}, {3, "Welcome"}}; for (auto x = std::make_reverse_iterator(a.cend()); x != std::make_reverse_iterator(a.cbegin()); ++x) { std::cout << x->first << ": " << x->second << std::endl; } return 0; }

输出

以上代码的输出如下:

3: Welcome
2: TutorialsPoint
2: TP
1: Tutorix

示例

在下面的示例中,我们将查找具有特定键的所有元素,并使用 cend() 函数迭代该范围。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> x = {{1, "Audi"}, {2, "Cruze"}, {2, "Sail"}, {3, "BMW"}}; auto a = x.equal_range(2); for (auto b = a.first; b != a.second && b != x.cend(); ++b) { std::cout << b->first << ": " << b->second << std::endl; } return 0; }

输出

如果我们运行以上代码,它将生成以下输出:

2: Cruze
2: Sail
multimap.htm
广告