Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Swapping sequences

We mentioned earlier that all basic sequences have a member function swap( ) that s designed to switch one sequence with another (but only for sequences of the same type). The member swap( ) makes use of its knowledge of the internal structure of the particular container in order to be efficient:

//: C07:Swapping.cpp {-bor}
// All basic sequence containers can be swapped.
//{L} Noisy
#include <algorithm>
#include <deque>
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
#include "Noisy.h"
#include "PrintContainer.h"
using namespace std;
ostream_iterator<Noisy> out(cout, " ");
template<class Cont> void testSwap(char* cname) {
Cont c1, c2;
generate_n(back_inserter(c1), 10, NoisyGen());
generate_n(back_inserter(c2), 5, NoisyGen());
cout << endl << cname << ":" << endl;
print(c1, "c1"); print(c2, "c2");
cout << "\n Swapping the " << cname << ":" << endl;
print(c1, "c1"); print(c2, "c2");
int main() {
testSwap<vector<Noisy> >("vector");
testSwap<deque<Noisy> >("deque");
testSwap<list<Noisy> >("list");
} ///:~

When you run this, you ll discover that each type of sequence container can swap one sequence for another without any copying or assignments, even if the sequences are of different sizes. In effect, you re completely swapping the resources of one object for another.

The STL algorithms also contain a swap( ), and when this function is applied to two containers of the same type, it uses the member swap( ) to achieve fast performance. Consequently, if you apply the sort( ) algorithm to a container of containers, you will find that the performance is very fast it turns out that fast sorting of a container of containers was a design goal of the STL.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire