This C++ program demonstrates the splice operation on std::list container. The splice operation removes the elements from one std::list and copies them into another. The program uses two versions of std::list::splice – one which moves only the element pointed by an iterator and second which moves the elements between the beginning and ending iterators.
Here is the source code of the C++ program which demonstrates the splice operation on std::list container. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Demonstrate Splice Operation on Lists
*/
#include <iostream>
#include <list>
#include <algorithm>
#include <string>
using namespace std;
void print(list<string>& l)
{
list<string>::const_iterator i = l.begin();
while(i != l.end()) {
cout << *i << " ";
i++;
}
cout << "\n";
}
int main() {
list<string> l1, l2;
l1.push_back(string("John Keats"));
l1.push_back(string("William Wordsworth"));
l1.push_back(string("Walt Whitman"));
l1.push_back(string("Robert Frost"));
l1.push_back(string("William Shakespeare"));
l1.push_back(string("Percy Shelley"));
cout << "List 1 : ";
print(l1);
cout << "List 2 : ";
print(l2);
l2.splice(l2.end(), l1, l1.begin());
cout << "After l2.splice(l2.end(), l1, l1.begin());\n";
cout << "List 1 : ";
print(l1);
cout << "List 2 : ";
print(l2);
l2.splice(l2.begin(), l1, ++(l1.begin()), --(l1.end()));
cout << "After l2.splice(l2.begin(), l1, ++(l1.begin()), --(l1.end()));\n";
cout << "List 1 : ";
print(l1);
cout << "List 2 : ";
print(l2);
}
$ gcc test.cpp $ a.out List 1 : John Keats William Wordsworth Walt Whitman Robert Frost William Shakespeare Percy Shelley List 2 : After l2.splice(l2.end(), l1, l1.begin()); List 1 : William Wordsworth Walt Whitman Robert Frost William Shakespeare Percy Shelley List 2 : John Keats After l2.splice(l2.begin(), l1, ++(l1.begin()), --(l1.end())); List 1 : William Wordsworth Percy Shelley List 2 : Walt Whitman Robert Frost William Shakespeare John Keats
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Practice Computer Science MCQs
- Check Programming Books
- Apply for Computer Science Internship
- Apply for C++ Internship
- Check Computer Science Books