欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > c++ STL swap用法和实现

c++ STL swap用法和实现

2024/10/25 14:30:18 来源:https://blog.csdn.net/zg260/article/details/140349152  浏览:    关键词:c++ STL swap用法和实现

一:功能

      交换两个值

二:用法 

#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-swapstd::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);
}

三:实现

#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';
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com