Apache C++ Standard Library Reference Guide

## iter_swap()

Library: Algorithms

    Function

- Local Index
- Summary
- Synopsis
- Description
- Example
- See Also
- Standards Conformance

### Local Index

No Entries

### Summary

Algorithm that exchanges values in two locations

### Synopsis

    #include <algorithm>

    namespace std {
      template <class ForwardIterator1, class ForwardIterator2>
      void iter_swap(ForwardIterator1, ForwardIterator2);
    }

### Description

The `iter_swap()` algorithm exchanges the values pointed to by the two iterators `a` and `b`.

### 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

### See Also

Iterators, `swap()`, `swap_ranges()`

### Standards Conformance

ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.2.2