Library: Algorithms
Function
Algorithm that exchanges a range of values in one location with those in another
#include <algorithm>
namespace std {
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator2
swap_ranges(ForwardIterator1 start1,
ForwardIterator1 finish1,
ForwardIterator2 start2);
}
The swap_ranges() algorithm exchanges corresponding values in two ranges, in the following manner:
For each non-negative integer n < (finish - start), the function exchanges *(start1 + n) with *(start2 + n)). After completing all exchanges, swap_ranges() returns an iterator that points to the end of the second container (in other words, start2 + (finish1 -start1)). The result of swap_ranges() is undefined if the two ranges [start, finish) and [start2, start2 + (finish1 - start1)) overlap.
//
// 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