C++ multimap::size() 函式



C++ 的std::multimap::size()函式用於返回multimap中元素的數量。multimap是一個關聯容器,它以鍵值對的形式儲存元素,允許具有相同鍵的多個元素。此函式提供了一種快速確定這些元素總數的方法。此函式的時間複雜度為常數,即 O(1)。

語法

以下是 std::multimap::size() 函式的語法。

size_type size() const noexcept;

引數

它不接受任何引數。

返回值

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

示例

讓我們來看下面的例子,我們將演示 size() 函式的使用。

#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 的大小。

#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() 函式查詢具有該鍵的所有元素,迭代器之間的距離給出具有該鍵的元素的數量。

#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 的元素並觀察輸出。

#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
廣告
© . All rights reserved.