如何使用Struct打印交换函数
How can I print my swap function with Struct
你能帮我吗,我如何打印我的swap3函数?我会非常感激的。我是编程的初学者
#include <iostream>
using namespace std;
struct Pair{
int x;
int y;
};
Pair* swap3(const Pair& p){
Pair *t = new Pair();
t->x = p.y;
t->y = p.x;
return t;
}
int main(){
int f = Pair(2,3);
swap3(f);
cout<<f<<endl;
return 0;
}
我的主要功能是假的吗?
您需要重载ostream
运算符:
friend std::ostream &operator<<(std::ostream &os, const Pair& pair) {
os << pair.x << " " << pair.y << 'n';
return os;
}
如果您对操作员的oveloading感到不舒服,您可以简单地单独打印元素:
cout<< f.x <<" "<< f.y <<'n';
构造f
的方式也是错误的(int
和Pair
不是同一类型(。您可以尝试列表初始化:
Pair f{2,3};
auto s = swap3(f);
cout<<f<<endl;
delete s;
请注意,您的代码中存在内存泄漏,因为您的函数返回一个指针,所以您不会存储它,也永远不会删除它
我建议使用智能指针来避免内存泄漏:
std::unique_ptr<Pair> swap3(const Pair& p){
auto t = make_unique<Pair>(Pair{});
t->x = p.y;
t->y = p.x;
return t;
}
Godbolt 直播
p.S。我不确定你想要交换什么,在你发布的代码中,你根本不需要指针。我认为掉期应该写成:
void swap3(Pair& p1, Pair& p2){
Pair tmp{p1.x, p1.y};
p1.x = p2.x;
p1.y = p2.y;
p2.x = tmp.x;
p2.y = tmp.y;
}
或:
void swap3(Pair& p){
Pair tmp{p.x, p.y};
p.x = tmp.y;
p.y = tmp.x;
}
Godbolt 直播
相关文章:
- 交换函数不是在 C++ 中交换 2D 数组的元素
- 选择排序时交换函数调用的数量和完成的交换次数是否相同?
- 在C++中使用 4 个交换函数修复程序
- 如何使用Struct打印交换函数
- 错误:使用复制和交换习惯用法的交换函数中"operator="的重载不明确
- 从递归向后选择排序函数调用 max 和交换函数
- 使用通用交换函数来缩短代码
- 快速排序中的交换函数给出错误的输出
- 为什么每个STL容器都具有将其定义为成员函数的交换函数
- 使用交换函数交换元素是可以的吗?
- 传递参数、参数、交换函数和随机数生成器
- 如何在这个交换函数(一个单独的链表)中找到错误
- 左值和右值引用的交换函数
- 使用指针的交换函数
- 排序算法的交换函数不适用于排序函数中的参数。
- 为什么使用std::swap不会在外部范围中隐藏其他交换函数
- 交换对象不实现移动语义时的交换函数
- 我如何制作constexpr交换函数
- 在c++中编写交换函数以重新分配结构数组中的成员值
- std::排序和自定义交换函数