Merging two sequences - C++ STL Algorithm

C++ examples for STL Algorithm:merge

Description

Merging two sequences

Demo Code

#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;
template<typename C>
void printContainer(const C& c, char delim = ',', ostream& out = cout) {
   printRange(c.begin(), c.end(), delim, out);
}

template<typename Fwd>
void printRange(Fwd first, Fwd last, char delim = ',', ostream& out = cout) {
   out << "{";
   while (first != last) {
      out << *first;// w  w  w  . j  av  a 2 s.c  om
      if (++first != last)
         out << delim << ' ';
   }
   out << "}" << endl;
}

int main() {

   vector<string> v1, v2, v3;

   v1.push_back("a");
   v1.push_back("c");
   v1.push_back("e");

   v2.push_back("b");
   v2.push_back("d");
   v2.push_back("f");

   v3.reserve(v1.size() + v2.size() + 1);

   merge(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter<vector<string> >(v3));

   printContainer(v3);

   random_shuffle(v3.begin(), v3.end());
   sort(v3.begin(), v3.begin() + v3.size() / 2);
   sort(v3.begin() + v3.size() / 2, v3.end());

   printContainer(v3);

   inplace_merge(v3.begin(), v3.begin() + 3, v3.end());

   printContainer(v3);

   list<string> lstStr1, lstStr2;

   lstStr1.push_back("F");
   lstStr1.push_back("R");
   lstStr1.push_back("B");
   lstStr1.push_back("C");

   lstStr2.push_back("A");
   lstStr2.push_back("M");
   lstStr2.push_back("S");
   lstStr2.push_back("W");

   lstStr1.sort();  // Sort these or merge makes garbage!
   lstStr2.sort();

   lstStr1.merge(lstStr2); // Note that this only works with other lists of the same type

   printContainer(lstStr1);
}

Result


Related Tutorials