Merging two lists isn’t only a popular homework assignment; rather, this task is sometimes needed in real world programming as well. Fortunately, you don’t have to reinvent the wheel anymore. STL’s list defines the member function merge(), which takes a second list as an argument and merges it into the original one. If both lists were sorted, merge() ensures that the merged list remains sorted. Note that after calling merge(), the second list becomes empty. Here’s an example:
#include using std::list;int main(){ list first; list second; // fill both lists first.push_back(1); first.push_back(8); // first is sorted second.push_back(2); second.push_back(10); // second is sorted // merge second into first first.merge(second); // at this point, second is empty and first // contains 4 elements in ascending order}