一:功能
交换两个值
二:用法
cpp
#include <format>
#include <iostream>
namespace Library {
struct Storage {
int value;
};
//支持swap操作
void swap(Storage& left, Storage& right) {
std::ranges::swap(left.value, right.value);
}
}
int main() {
int a = 1, b = 2;
std::ranges::swap(a, b); // 3-step-swap
std::format_to(std::ostreambuf_iterator(std::cout),
"a == {}, b == {}\n", a, b);
Library::Storage j{2}, k{3};
std::ranges::swap(j, k); // calls custom Library::swap()
std::format_to(std::ostreambuf_iterator(std::cout),
"j == {}, k == {}\n", j.value, k.value);
}
三:实现
cpp
#include <algorithm>
#include <iostream>
template<typename T>
void my_swap(T &a,T &b) noexcept
{
T temp = std::move(a);
a = std::move(b);
b = std::move(temp);
}
int main()
{
int a = 5, b = 3;
std::cout << a << ' ' << b << '\n';
my_swap(a, b);
std::cout << a << ' ' << b << '\n';
}