blob: 1df12373e4a6fb009aeaa21ac4798e2a6bd1df80 [file] [log] [blame]
 swap()
Apache C++ Standard Library Reference Guide

swap()

Library:  Algorithms

Function

Local Index

No Entries

Summary

Algorithm that exchanges values

Synopsis

#include <algorithm>

namespace std {
template <class T>
void swap(T& a, T& b)
}

Description

The swap() algorithm exchanges the values of a and b. The effect is:

T tmp = a
a = b
b = tmp

Example

//
//  swap.cpp
//

#include <algorithm>   // for copy, iter_swap
#include <iostream>    // for cout, endl
#include <iterator>    // for ostream_iterator
#include <vector>      // for vector

int main ()
{
typedef std::ostream_iterator<int, char,
std::char_traits<char> > Iter;

const int a[] = { 6, 7, 8, 9, 10, 1, 2, 3, 4, 5 };

// Set up a vector
std::vector<int, std::allocator<int> >
v (a, a + sizeof a / sizeof *a);

// Output original vector.
std::cout << "For the vector: ";
std::copy (v.begin (), v.end (), Iter (std::cout, " "));

// Swap the first five elements with the last five elements
std::swap_ranges (v.begin (), v.begin () + 5,
v.begin () + 5);

// Output result
std::cout << "\n\nSwapping the first five elements "
<< "with the last five gives: \n     ";

std::copy (v.begin (), v.end (), Iter (std::cout," "));

// Now an example of iter_swap -- swap first
// and last elements.
std::iter_swap (v.begin(), v.end () - 1);

// Output result
std::cout << "\n\nSwapping the first and last elements "
<< "gives: \n     ";
std::copy (v.begin (), v.end (), Iter (std::cout, " "));

std::cout << std::endl;

return 0;
}

Program Output:
For the vector: 6 7 8 9 10 1 2 3 4 5

Swapping the first five elements with the last five gives:
1 2 3 4 5 6 7 8 9 10

Swapping the first and last elements gives:
10 2 3 4 5 6 7 8 9 1