📜  C++ STL中的unordered_multimap运算符=(1)

📅  最后修改于: 2023-12-03 15:29:51.092000             🧑  作者: Mango

C++ STL中的unordered_multimap运算符=

介绍

在C++ STL(标准模板库)中,unordered_multimap是一种关联容器(associative container),它是用哈希表实现的,可以存储键值对(key-value pair)。

unordered_multimap允许存储具有相同键(key)的多个值(value),因此可以用来处理一对多的关系。

unordered_multimap是C++11标准中新增的容器,它的定义位于<unordered_map>头文件中。

unordered_multimap使用hash函数将键值转换为索引值,然后存储在对应的桶(bucket)中,这使得unordered_multimap的查找、插入和删除操作的平均时间复杂度为常数级别(O(1))。

运算符=

unordered_multimap的运算符=(赋值运算符)的作用是将一个unordered_multimap对象赋值给另一个unordered_multimap对象。

unordered_multimap的赋值运算符的语法如下:

unordered_multimap& operator=(const unordered_multimap& umap);

其中,umap是待赋值的unordered_multimap对象。

赋值运算符会使左侧的unordered_multimap对象的内容被替换为右侧的unordered_multimap对象的内容。如果左侧的unordered_multimap对象原本就有内容,那么在赋值运算符执行前,它的内容会被销毁。

赋值运算符返回一个左值引用,表示被赋值后的unordered_multimap对象。

下面是一个示例程序,演示了unordered_multimap的赋值运算符的使用:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_multimap<int, std::string> old_umap = {{1, "one"}, {2, "two"}, {3, "three"}};
    std::unordered_multimap<int, std::string> new_umap = {{4, "four"}, {5, "five"}, {6, "six"}};

    std::cout << "old_umap: ";
    for (auto it = old_umap.begin(); it != old_umap.end(); ++it) {
        std::cout << "{" << it->first << ", " << it->second << "} ";
    }
    std::cout << std::endl;

    std::cout << "new_umap: ";
    for (auto it = new_umap.begin(); it != new_umap.end(); ++it) {
        std::cout << "{" << it->first << ", " << it->second << "} ";
    }
    std::cout << std::endl;

    old_umap = new_umap;

    std::cout << "old_umap: ";
    for (auto it = old_umap.begin(); it != old_umap.end(); ++it) {
        std::cout << "{" << it->first << ", " << it->second << "} ";
    }
    std::cout << std::endl;

    return 0;
}

输出结果为:

old_umap: {1, one} {2, two} {3, three} 
new_umap: {4, four} {5, five} {6, six} 
old_umap: {5, five} {4, four} {6, six} 

可见,赋值运算符将右侧的unordered_multimap对象的内容赋值给了左侧的unordered_multimap对象,并且在赋值前,左侧的unordered_multimap对象的内容已经被销毁了。