C++ examples for STL Algorithm:merge
Using merge() and inplace_merge() to merge vector and deque
#include <iostream> #include <vector> #include <deque> #include <list> #include <algorithm> using namespace std; template<class InIter> void show_range(const char *msg, InIter start, InIter end); int main()//from ww w. j a v a2 s. co m { vector<char> v; deque<char> dq; list<char> result(26); list<char>::iterator res_end; // First, demonstrate merge(). for(int i=0; i < 26; i+=2) v.push_back('A'+i); for(int i=0; i < 26; i+=2) dq.push_back('B'+i); show_range("Original contents of v:\n", v.begin(), v.end()); cout << endl; show_range("Original contents of dq:\n", dq.begin(), dq.end()); cout << endl; // Merge v with dq. res_end = merge(v.begin(), v.end(), dq.begin(), dq.end(), result.begin()); show_range("Result of merging v with dq:\n", result.begin(), res_end); cout << "\n\n"; // Now, demonstrate inplace_merge(). vector<char> v2; for(int i=0; i < 26; i+=2) v2.push_back('B'+i); for(int i=0; i < 26; i+=2) v2.push_back('A'+i); show_range("Original contents of v2:\n", v2.begin(), v2.end()); cout << endl; // Merge two ranges within v2. inplace_merge(v2.begin(), v2.begin()+13, v2.end()); show_range("Contents of v2 after in-place merge:\n", v2.begin(), v2.end()); return 0; } // Show a range of elements. template<class InIter> void show_range(const char *msg, InIter start, InIter end) { InIter itr; cout << msg; for(itr = start; itr != end; ++itr) cout << *itr << " "; cout << endl; }