C++ multimap::end() 函式



C++ 的 std::multimap::end() 函式用於返回一個指向容器末尾元素之後位置的迭代器。此元素充當佔位符,不能用於解引用。它主要用於在迭代期間指示 multimap 的結尾,允許函式正確地迴圈遍歷所有元素。返回的迭代器用於確定迭代或元素搜尋何時停止,確保已處理所有元素範圍。

語法

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

iterator end() noexcept;
const_iterator end() const noexcept;

引數

它不接受任何引數。

返回值

此函式返回一個指向末尾元素之後位置的迭代器。

示例

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

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert({1, "A"});
    a.insert({2, "B"});
    a.insert({3, "C"});
    std::multimap<int, std::string>::iterator x = a.end();
    for (x = --a.end(); x != --a.begin(); --x) {
        std::cout << x->first << " => " << x->second << std::endl;
    }
    return 0;
}

輸出

以上程式碼的輸出如下:

3 => C
2 => B
1 => A

示例

考慮下面的示例,我們將檢查 multimap 是否為空。

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

輸出

以上程式碼的輸出如下:

Multimap is empty.

示例

在下面的示例中,我們將刪除具有特定鍵的元素,並使用 end() 函式迭代並列印剩餘的元素。

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

輸出

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

2 => Beats
3 => Cruze

示例

下面的示例將使用 find() 定位鍵,如果找到鍵則列印元素,否則檢查 end() 以確認元素不存在。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "A"}, {2, "B"}, {3, "C"}};
    auto x = a.find(3);
    if (x != a.end()) {
        std::cout << "Element Found : " << x->first << " => " << x->second << std::endl;
    } else {
        std::cout << "Element Not Found :" << std::endl;
    }
    return 0;
}

輸出

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

Element Not Found
multimap.htm
廣告