一:功能
交换两个迭代器指向的元素值,一般用在模板中
二:使用
#include <vector>
#include <iostream>template <typename It, typename Cond>requires std::forward_iterator<It> && std::indirectly_swappable<It,It> && std::predicate<Cond, It>
auto partition(It first, It last, Cond cond) {while (first != last && cond(first)) ++first;if (first == last) return last;for (auto it = std::next(first); it != last; it++) {if (!cond(it)) continue;std::iter_swap(it, first);++first;}return first;
}int main() {std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9};partition(data.begin(), data.end(), [](auto it) {return *it % 2 == 0;});for (auto v : data) {std::cout << v << " ";}std::cout << "\n";
}
三:实现
#include <algorithm>
#include <iostream>
#include <random>
#include <string_view>
#include <vector>template<class ForwardIt1, class ForwardIt2>
constexpr //< since C++20
void my_iter_swap(ForwardIt1 a, ForwardIt2 b)
{using std::swap;swap(*a, *b);
}template<class ForwardIt>
void selection_sort(ForwardIt begin, ForwardIt end)
{for (ForwardIt it = begin; it != end; ++it)my_iter_swap(it, std::min_element(it, end));
}void println(std::string_view rem, std::vector<int> const& v)
{std::cout << rem;for (int e : v)std::cout << e << ' ';std::cout << '\n';
}template<int min, int max>
int rand_int()
{static std::uniform_int_distribution dist(min, max);static std::mt19937 gen(std::random_device{}());return dist(gen);
}int main()
{std::vector<int> v;std::generate_n(std::back_inserter(v), 20, rand_int<-9, +9>);std::cout << std::showpos;println("Before sort: ", v);selection_sort(v.begin(), v.end());println("After sort: ", v);
}