merge()は2つのソートされたコンテナをマージします。
merge()の書式は次のとおりです。
#include <algorithm>
template oiter merge(iiter1 first1, iiter1 last1, iiter2 first2, iiter2 last2, oiter x);
template oiter merge(iiter1 first1, iiter1 last1, iiter2 first2, iiter2 last2, oiter x, pred pr);
void list::merge(list& x);
void list::merge(list& x, greater pr);
引数first1マージする1個目のコンテナの最初の要素の反復子、last1はマージする1個目のコンテナの最後の要素の反復子です。
first2はマージする第二のコンテナの最初の要素の反復子、last2はマージする第二のコンテナの最後の要素の反復子です。
xは結果を保存するコンテナの最初の反復子、prは各要素に適用する述語です。
最初の書式と第2の書式のアルゴリズムは、2つのソートされたコンテナをマージして、別のコンテナに入れます。
第3の書式と最後の書式の関数は、引数のリストをマージします。
次の例は、2個のリストを作成して、第3のリストにマージするプログラムの例です。
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <list>
#include <algorithm>
void print(const int p) {
std::cout << p << ", ";
}
int main(int argc, char* argv[])
{
std::list<int> lst1, lst2, lst3(10);
srand((unsigned)time(NULL));
// コンテナに値をプッシュする
for (int i = 0; i < 5; ++i) {
lst1.push_back(rand() % 100);
}
// コンテナに値をプッシュする
for (int i = 0; i < 3; ++i) {
lst2.push_back(rand() % 100);
}
// コンテナの要素を出力する
std::cout << "lst1:";
for_each(lst1.begin(), lst1.end(), print);
std::cout << std::endl;
std::cout << "lst2:";
for_each(lst2.begin(), lst2.end(), print);
std::cout << std::endl;
lst1.sort();
lst2.sort();
// コンテナの要素を出力する
std::cout << "lst1(sorted):";
for_each(lst1.begin(), lst1.end(), print);
std::cout << std::endl;
// コンテナの要素を出力する
std::cout << "lst2(sorted):";
for_each(lst2.begin(), lst2.end(), print);
std::cout << std::endl;
merge(lst1.begin(), lst1.end(), lst2.begin(), lst2.end(), lst3.begin());
// コンテナの要素を出力する
std::cout << "lst3:";
for_each(lst3.begin(), lst3.end(), print);
std::cout << std::endl;
return 0;
}
実行結果は次のようになります。
st1:21, 11, 67, 27, 18,
lst2:48, 81, 28,
lst1(sorted):11, 18, 21, 27, 67,
lst2(sorted):28, 48, 81,
lst3:11, 18, 21, 27, 28, 48, 67, 81, 0, 0,