C++ multimap::size() 函数



C++ 的std::multimap::size()函数用于返回multimap中元素的数量。multimap是一个关联容器,它以键值对的形式存储元素,允许具有相同键的多个元素。此函数提供了一种快速确定这些元素总数的方法。此函数的时间复杂度为常数,即 O(1)。

语法

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

size_type size() 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.

返回值

此函数返回容器中元素的数量。

示例

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

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; a.insert({1, "apple"}); a.insert({2, "banana"}); std::cout << "Size of the multimap is: " << a.size() << std::endl; return 0; }

输出

以下是上述代码的输出:

Size of the multimap is: 2

示例

考虑另一种情况,我们获取初始大小,然后插入一些元素并获取 multimap 的大小。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; a.insert({1, "TP"}); std::cout << "Initial size: " << a.size() << std::endl; a.insert({2, "Tutorix"}); a.insert({3, "TutorialsPoint"}); std::cout << "Size after insertion: " << a.size() << std::endl; return 0; }

输出

上述代码的输出如下:

Initial size: 1
Size after insertion: 3

示例

在下面,我们将使用 size() 函数获取 multimap 的大小,然后应用 equal_range() 函数查找具有该键的所有元素,迭代器之间的距离给出具有该键的元素的数量。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; a.insert({1, "Hi"}); a.insert({2, "Hello"}); a.insert({2, "Vanakam"}); std::cout << "Size of the multimap: " << a.size() << std::endl; auto x = a.equal_range(2); int count = std::distance(x.first, x.second); std::cout << "Elements with given key : " << count << std::endl; return 0; }

输出

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

Size of the multimap: 3
Elements with given key : 2

示例

下面的示例中,我们将用 3 个元素初始化 multimap,键 1 出现两次,然后删除键 1 的元素并观察输出。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; a.insert({1, "AB"}); a.insert({1, "BC"}); a.insert({2, "CD"}); std::cout << "Size before erasing: " << a.size() << std::endl; a.erase(1); std::cout << "Size after erasing given key: " << a.size() << std::endl; return 0; }

输出

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

Size before erasing: 3
Size after erasing given key: 1
multimap.htm
广告