Namespaces
Variants

std::map<Key,T,Compare,Allocator>:: merge

From cppreference.net

template < class C2 >
void merge ( std:: map < Key, T, C2, Allocator > & source ) ;
(1) (自 C++17 起)
(自 C++26 起为 constexpr)
template < class C2 >
void merge ( std:: map < Key, T, C2, Allocator > && source ) ;
(2) (自 C++17 起)
(自 C++26 起为 constexpr)
template < class C2 >
void merge ( std:: multimap < Key, T, C2, Allocator > & source ) ;
(3) (自 C++17 起)
(自 C++26 起为 constexpr)
template < class C2 >
void merge ( std:: multimap < Key, T, C2, Allocator > && source ) ;
(4) (自 C++17 起)
(自 C++26 起为 constexpr)

尝试提取(“拼接”) source 中的每个元素,并使用 * this 的比较对象将其插入到 * this 中。 如果 * this 中存在与 source 中元素键值相等的元素,则不会从 source 中提取该元素。 若 get_allocator ( ) == source. get_allocator ( ) false ,则行为未定义。

不会复制或移动任何元素,仅重新指向容器节点的内部指针。所有指向被转移元素的指针和引用仍然有效,但现在指向的是 * this ,而非 source

目录

参数

source - 用于转移节点的兼容容器

异常处理

除非比较操作抛出异常,否则不会抛出异常。

复杂度

给定 S size ( ) N source. size ( )

1-4) S·log(S+N)

示例

#include <iostream>
#include <map>
#include <string>
int main()
{
    std::map<int, std::string> ma{{1, "apple"}, {5, "pear"}, {10, "banana"}};
    std::map<int, std::string> mb{{2, "zorro"}, {4, "batman"}, {5, "X"}, {8, "alpaca"}};
    std::map<int, std::string> u;
    u.merge(ma);
    std::cout << "ma.size(): " << ma.size() << '\n';
    u.merge(mb);
    std::cout << "mb.size(): " << mb.size() << '\n';
    std::cout << "mb.at(5): " << mb.at(5) << '\n';
    for (const auto& kv : u)
        std::cout << kv.first << ", " << kv.second << '\n';
}

输出:

ma.size(): 0
mb.size(): 1
mb.at(5): X
1, apple
2, zorro
4, batman
5, pear
8, alpaca
10, banana

参见

(C++17)
从容器中提取节点
(公开成员函数)
插入元素 或节点 (自 C++17 起)
(公开成员函数)