CppDS.com

C++ 98 11 14 17 20 手册

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

来自cppreference.com
< cpp‎ | container‎ | map

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

试图提取(“接合”) source 中每个元素,并用 *this 的比较对象插入到 *this 。 若 *this 中有元素,其键等价于来自 source 中元素的键,则不从 source 提取该元素。 不复制或移动元素,只会重指向容器结点的内部指针。指向被转移元素的所有指针和引用保持合法,但现在指代到 *this 中而非到 source 中。

get_allocator() != source.get_allocator() 则行为未定义。

参数

source - 传递结点来源的兼容容器

返回值

(无)

异常

不抛异常,除非比较抛出。

复杂度

N*log(size()+N)) ,其中 N 为 source.size()

示例

#include <map>
#include <iostream>
#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(auto const &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 起)
(公开成员函数)
关闭