Friday, January 1, 2010

STL LIST- SPLICE

Move elements from list to list

Moves elements from list x into the list container at the specified position, effectively inserting the specified elements into the container and removing them from x.

This increases the container size by the amount of elements inserted, and reduces the size of x by the same amount ( whenever x is not the same as *this ).

The operation does not involve the construction or destruction of any element object and, except for the third version, it is performed in constant time.

The iterators that pointed to moved elements are no longer valid.


// splicing lists
#include < iostream >
#include < list >
using namespace std;

int main ()
{
list< int > mylist1, mylist2;
list::iterator it;

// set some initial values:
for (int i=1; i<=4; i++)
mylist1.push_back(i); // mylist1: 1 2 3 4

for (int i=1; i<=3; i++)
mylist2.push_back(i*10); // mylist2: 10 20 30

it = mylist1.begin();
++it; // points to 2

mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4
// mylist2 (empty)
// "it" still points to 2 (the 5th element)

mylist2.splice (mylist2.begin(),mylist1, it);
// mylist1: 1 10 20 30 3 4
// mylist2: 2
// "it" is now invalid.
it = mylist1.begin();
advance(it,3); // "it" points now to 30

mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
// mylist1: 30 3 4 1 10 20

cout << "mylist1 contains:";
for (it=mylist1.begin(); it!=mylist1.end(); it++)
cout << " " << *it;

cout << "\nmylist2 contains:";
for (it=mylist2.begin(); it!=mylist2.end(); it++)
cout << " " << *it;
cout << endl;

return 0;
}

Output:
mylist1 contains: 30 3 4 1 10 20
mylist2 contains: 2

No comments:

Post a Comment