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 起)
(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 - 傳遞節點來源的兼容容器

異常

不拋異常,除非比較操作有拋出。

[編輯] 複雜度

給定 Ssize()Nsource.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 起)
(公開成員函數) [編輯]