
Module: Standard C++ Library Library: Algorithms
Function
Algorithm that exchanges values
#include <algorithm>
namespace std {
template <class T>
void swap(T& a, T& b)
}
The swap() algorithm exchanges the values of a and b. The effect is:
T tmp = a a = b b = tmp
//
// 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
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.2.2
Copyright (c) 1994-2006 Rogue Wave Software, a Quovadx Division.
Licensed under the Apache License, Version 2.0.
Contact Rogue Wave about documentation or support issues. You can also seek help from other developers through the Apache stdcxx community (see below).