Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: All
Feb 22, 2000

Merging Two Lists

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 <list>
using std::list;

int main()
{
 list <int> first;
 list <int> 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
}
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap