std::map merge() 方法
- 自 C++17 起
// (1) Non const version only
template<class C2>
void merge( std::map<Key, T, C2, Allocator>& source );
// (2) Non const version only
template<class C2>
void merge( std::map<Key, T, C2, Allocator>&& source );
// (3) Non const version only
template<class C2>
void merge( std::multimap<Key, T, C2, Allocator>& source );
// (4) Non const version only
template<class C2>
void merge( std::multimap<Key, T, C2, Allocator>&& source );
尝试提取(“拼接”)源中的每个元素,并使用 *this
的比较对象将其插入到 *this
中。如果 *this
中存在一个键与 source
中元素的键等价的元素,则该元素不会从 source
中提取。
不复制或移动任何元素,只重新指向容器节点的内部指针。所有指向已转移元素的指针和引用仍然有效,但现在它们指向 *this
,而不是源。
未定义行为
如果 get_allocator() != source.get_allocator()
,则行为未定义。
参数
source
- 用于从中转移节点的兼容容器
返回值
(无)
复杂度
N * log(size() + N)),其中 N 是 source.size()
。
异常
除非比较抛出,否则不抛出。
示例
Main.cpp
#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