名前空間
変種
操作

std::list<T,Allocator>::merge

提供: cppreference.com
< cpp‎ | container‎ | list
 
 
 
 
void merge( list& other );
(1)
void merge( list&& other );
(1) (C++11以上)
template<class Compare>
void merge( list& other, Compare comp );
(2)
template<class Compare>
void merge( list&& other, Compare comp );
(2) (C++11以上)

2つのソート済みリストを1つにマージします。 リストは昇順にソートされていなければなりません。

要素はコピーされません。 操作の後、コンテナ other は空になります。 other*this と同じオブジェクトを参照する場合、この関数は何もしません。 get_allocator()!= other.get_allocator() の場合、動作は未定義です。 どのイテレータも参照も無効化されません。 ただし移動される要素を指すイテレータは other ではなく *this 内を指すようになります。 最初のバージョンは要素を比較するために operator< を使用します。 2番目のバージョンは指定された比較関数 comp を使用します。

この操作は安定です。 2つのリスト内の等しい要素に対しては、 *this 由来の要素が other 由来の要素よりも常に前に来ます。 *this および other の等しい要素の順序は変更されません。

目次

[編集]引数

other - マージする別のコンテナ
comp - 最初の要素が2番目の要素より小さい (に順序づけられる) 場合に ​true を返す、比較関数オブジェクト (Compare の要件を満たすオブジェクト)。

比較関数のシグネチャは以下と同等なものであるべきです。

 bool cmp(const Type1 &a, const Type2 &b);

シグネチャが const& を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、 Type1 型および Type2 型 (およびそれらの const 修飾された型) のすべての値を値カテゴリに関わらず受理できなければなりません (そのため Type1 & は許されません。 また Type1 に対してムーブがコピーと同等でなければ Type1 も許されません(C++11以上))。
Type1 および Type2 は、どちらも list<T,Allocator>::const_iterator 型のオブジェクトの逆参照から暗黙に変換可能なものでなければなりません。 ​

[編集]戻り値

(なし)

[編集]例外

例外が投げられた場合、この関数は効果を持ちません (強い例外保証)。 ただしその例外が比較関数から投げられた場合は除きます。

[編集]計算量

高々 std::distance(begin(), end())+std::distance(other.begin(), other.end())-1 回の比較。

[編集]

#include <iostream>#include <list>   std::ostream& operator<<(std::ostream& ostr, conststd::list<int>& list){for(auto&i : list){ ostr <<" "<< i;}return ostr;}   int main(){std::list<int> list1 ={5,9,0,1,3};std::list<int> list2 ={8,7,2,6,4};   list1.sort(); list2.sort();std::cout<<"list1: "<< list1 <<"\n";std::cout<<"list2: "<< list2 <<"\n"; list1.merge(list2);std::cout<<"merged: "<< list1 <<"\n";}

出力:

list1: 0 1 3 5 9 list2: 2 4 6 7 8 merged: 0 1 2 3 4 5 6 7 8 9

[編集]関連項目

別の list から要素を移動します
(パブリックメンバ関数)[edit]
close