C++ multimap::crend() 函数



C++ 的 std::multimap::crend() 函数用于返回一个指向 multimap 中第一个元素之前元素的常量反向迭代器,标志着它反向顺序的结尾。此迭代器不能用于修改它指向的元素。它用于反向迭代 multimap 而无需更改元素,从而确保只读访问。此函数的时间复杂度是常数,即 O(1)。

语法

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

const_reverse_iterator crend() 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.

返回值

此函数返回一个常量反向迭代器。

示例

在下面的示例中,我们将演示 crend() 函数的用法。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = {{2, "B"}, {1, "C"}, {3, "A"}}; for (auto x = a.crbegin(); x != a.crend(); ++x) { std::cout << x->first << ": " << x->second << std::endl; } return 0; }

输出

以下是上述代码的输出:

3: A
2: B
1: C

示例

考虑以下示例,我们将检查 multimap 是否为空。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; if (a.crbegin() == a.crend()) { std::cout << "Multimap is empty." << std::endl; } else { std::cout << "Multimap is not empty." << std::endl; } return 0; }

输出

上述代码的输出如下:

Multimap is empty.

示例

在下面的示例中,我们将查找 multimap 中最大的键。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = {{4, "A"}, {3, "B"}, {1, "C"}}; auto x = a.crbegin(); if (x != a.crend()) { std::cout << "" << x->first << std::endl; } return 0; }

输出

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

4

示例

以下示例将计算 multimap 中值为“B”的元素个数。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = {{3, "A"}, {1, "B"}, {1, "B"}, {1, "B"}}; int x = 0; for (auto y = a.crbegin(); y != a.crend(); ++y) { if (y->second == "B") { ++x; } } std::cout << " " << x << std::endl; return 0; }

输出

让我们编译并运行上述程序,这将产生以下结果:

3
multimap.htm
广告