C++ multimap::crbegin() 函式



C++ 的 std::multimap::crbegin() 函式用於返回指向最後一個元素的常量反向迭代器,允許從容器的末尾到開頭進行只讀遍歷。此函式確保元素以反序訪問,並且不允許修改。它主要用於只讀操作的場景,例如以反序訪問和檢查元素。此函式的時間複雜度為常數,即 O(1)。

語法

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

const_reverse_iterator crbegin() const noexcept;

引數

它不接受任何引數。

返回值

此函式返回一個常量反向迭代器。

示例

讓我們看下面的例子,我們將演示 crbegin() 函式的基本用法。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "Hello"},{3, "Namaste"}, {2, "Hi"}};
    auto x = a.crbegin();
    std::cout <<"(" << x->first << ", " << x->second << ")\n";
    return 0;
}

輸出

以上程式碼的輸出如下:

(3, Namaste)

示例

考慮下面的例子,我們將使用 crbegin() 以反序迭代 multimap。它迭代直到到達 crend()。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{2, "TP"}, {3, "TutorialsPoint"}, {1, "Tutorix"}};
    for (auto x = a.crbegin(); x != a.crend(); ++x) {
        std::cout << "(" << x->first << ", " << x->second << ")\n";
    }
    return 0;
}

輸出

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

(3, TutorialsPoint)
(2, TP)
(1, Tutorix)

示例

在下面的示例中,我們將以反序查詢特定的元素。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{3, "BMW"}, {1, "Cruze"}, {2, "Sail"}};
    for (auto x = a.crbegin(); x != a.crend(); ++x) {
        if (x->first == 1) {
            std::cout << "" << x->second << std::endl;
            break;
        }
    }
    return 0;
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Cruze

示例

以下是以反序比較值的示例。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> x = {
        {1, "A"}, {2, "B"}, {3, "C"}
    };
    std::multimap<int, std::string> y = {
        {3, "C"}, {2, "B"}, {1, "A"}
    };
    bool equal = std::equal(x.crbegin(), x.crend(), y.crbegin(), y.crend());
    std::cout << (equal ? "Multimaps are equal." : "Multimaps are not equal.") << '\n';
    return 0;
}

輸出

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

Multimaps are equal.
multimap.htm
廣告