C++ multimap::upper_bound() 函式



C++ 的 std::multimap::upper_bound() 函式用於返回一個迭代器,該迭代器指向大於指定鍵的第一個元素。它對於查詢可以在不破壞排序順序的情況下插入新元素的位置非常有用。與 map 不同,multimap 允許重複鍵,因此 upper_bound() 提供對大於鍵的第一個元素的訪問,而不是精確匹配。此函式的時間複雜度是對數級的,即 O(log n)。

語法

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

iterator upper_bound (const key_type& k);
const_iterator upper_bound (const key_type& k) const;

引數

  • k − 表示要搜尋的鍵。

返回值

此函式返回容器中第一個元素的迭代器。

示例

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

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "AB"}, {2, "BC"}, {3, "CD"}, {4, "DE"}
    };
    auto x = a.upper_bound(2);
    if (x != a.end()) {
        std::cout << "First element greater than key is : ";
        std::cout << x->first << " --> " << x->second << std::endl;
    } else {
        std::cout << "No elements is greater than key." << std::endl;
    }
    return 0;
}

輸出

以下是上述程式碼的輸出:

First element greater than key is : 3 --> CD

示例

考慮另一種情況,我們將迴圈中使用 upper_bound() 函式。

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

輸出

上述程式碼的輸出如下:

2 --> Hi
3 --> Hello
3 --> Vanakam

示例

在下面的示例中,我們將結合使用 upper_bound() 函式和 equal_range() 函式。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "TP"}, {1, "TutorialsPoint"}, {2, "Tutorix"}, {3, "Welcome"}
    };
    auto x = a.equal_range(1);
    auto y = a.upper_bound(1);
    std::cout << "Elements with given key : " << std::endl;
    for (auto z = x.first; z != x.second; ++z) {
        std::cout << z->first << " --> " << z->second << std::endl;
    }
    if (y != a.end()) {
        std::cout << "First element greater than key is :  ";
        std::cout << y->first << " --> " << y->second << std::endl;
    } else {
        std::cout << "No elements is greater than key." << std::endl;
    }
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Elements with given key : 
1 --> TP
1 --> TutorialsPoint
First element greater than key is :  2 --> Tutorix
multimap.htm
廣告