C++ multimap::operator=() 函式



C++ 的std::multimap::operator=()函式用於將一個 multimap 的內容賦值給另一個 multimap,從而實現高效地複製鍵值對。當呼叫此函式時,它會將源 multimap 中的所有元素複製到目標 multimap,並保持排序順序。

此函式有 3 個多型變體:使用複製版本、移動版本和初始化列表版本(您可以在下面找到所有變體的語法)。

此函式不會合並元素,它會用源 multimap 的內容替換目標 multimap 的內容。

語法

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

multimap& operator= (const multimap& x);
or	
multimap& operator= (multimap&& x);
or	
multimap& operator= (initializer_list<value_type> il);

引數

  • x - 指示另一個相同型別的 multimap 物件。
  • il - 指示一個 initializer_list 物件。

返回值

此函式返回 this 指標。

示例

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

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert({1, "TP"});
    a.insert({2, "TutorialsPoint"});
    std::multimap<int, std::string> b;
    b = a;
    for (const auto& pair : b) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

輸出

以上程式碼的輸出如下:

1: TP
2: TutorialsPoint

示例

考慮下面的例子,我們將進行自賦值並觀察輸出。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "Hi"}, {1, "Hello"}};
    a = a;
    for (const auto& pair : a) {
        std::cout << pair.first << " : " << pair.second << std::endl;
    }
    return 0;
}

輸出

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

1 : Hi
1 : Hello

示例

在下面的例子中,我們將應用 operator=() 將內容賦值給空的 multimap。

#include <iostream>
#include <map>
int main() {
    std::multimap<int, std::string> a = {{3, "Cruze"}, {2, "Sail"}};
    std::multimap<int, std::string> b;
    b = a;
    for (const auto& pair : b) {
        std::cout << pair.first << " : " << pair.second << std::endl;
    }
    return 0;
}

輸出

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

2 : Sail
3 : Cruze
multimap.htm
廣告