Defined in header <algorithm> | ||
---|---|---|
template< class ForwardIt1, class ForwardIt2 > void iter_swap( ForwardIt1 a, ForwardIt2 b ); |
Swaps the values of the elements the given iterators are pointing to.
a, b | - | iterators to the elements to swap |
Type requirements | ||
-ForwardIt1, ForwardIt2 must meet the requirements of ForwardIterator . |
||
-*a, *b must meet the requirements of Swappable . |
(none).
constant.
The following is an implementation of selection sort in C++
#include <random> #include <vector> #include <iostream> #include <algorithm> #include <functional> #include <iterator> template<class ForwardIt> void selection_sort(ForwardIt begin, ForwardIt end) { for (ForwardIt i = begin; i != end; ++i) std::iter_swap(i, std::min_element(i, end)); } int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(-10, 10); std::vector<int> v; generate_n(back_inserter(v), 20, bind(dist, gen)); std::cout << "Before sort: "; copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); selection_sort(v.begin(), v.end()); std::cout << "\nAfter sort: "; copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; }
Output:
swaps the values of two objects (function template) |
|
swaps two ranges of elements (function template) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/algorithm/iter_swap