c++ - Is there a way to swap 2 structs?
问题描述
In c++ you can swap 2 numbers without 3rd variable:
int x = 10;
int y = 5;
x ^= y;
y ^= x;
x ^= y; //x = 5, y = 10
So I wonder if there is a similar way to swap 2 structs without 3rd variable:
struct Position{int x, y;};
int main()
{
Position firstPose{x = 10, y = 5;};
Position secPose{x = 5, y = 10;};
//Now I want to swap firstPose with secPose.
}
Is this possible? if so; how to do it
解决方案
There is no a standard way to swap two structure without an intermediate copy. Arguably, one of the main benefit of swap "is" the intermediate copy, this wonderful article explain how swap is a crucial part to achieve "strong exception guarantee". https://www.stroustrup.com/except.pdf
Furthermore, if the goal is to not make a copy of the struct (because is resource intensive) you can design your class using the pimpl idiom and swap just the pointer (you will still have a third variable but it will be just the raw pointer to the structure).
If you want to use C++ effectively make yourself familiar with exception safety, it is truly of of the area where the language gives its best
A bit old but still good article: http://www.gotw.ca/gotw/008.htm
At the end, the final solution is create a custom swap function:
#include <iostream>
#include <string>
struct Position{int x, y;};
void swap(Position& a, Position& b)
{
a.x ^= b.x;
b.x ^= a.x;
a.x ^= b.x;
a.y ^= b.y;
b.y ^= a.y;
a.y ^= b.y;
}
int main()
{
Position a = { 10, 100};
Position b = { 20, 200};
swap(a, b);
std::cout << "a:" << a.x << "," << a.y << std::endl;
std::cout << "b:" << b.x << "," << b.y << std::endl;
}
IMHO, the last option is more for personal amusement than real production code.
推荐阅读
- ios - 为什么tableview中的数据总是随机排序的?
- python - 无法腌制“dict_keys”对象 - 带有键规则的 dict 验证器
- mysql - Sql 查询交叉变换或透视?
- python - 使用 BeautifulSoup 进行抓取,值不干净
- python - 在元素个数为偶数的情况下不除以两个元素之和的中位数
- pandas - Groupby 转换到 Pandas 中的列表不起作用
- uuid - UUID 在 Minecraft bungeeCord 网络中为同一个人以不同方式保存
- reactjs - 如何避免 React Hooks 的重新渲染
- java - 我想替换java段落中的整个单词,但它也在替换匹配的字符。不知道该怎么做
- javascript - SyntaxError: 预期的表达式,得到 '&' (Django)