简体   繁体   English

如何使用 Struct 打印我的交换 function

[英]How can I print my swap function with Struct

Could you help me, how can I print my swap3 function?你能帮我吗,我怎样才能打印我的swap3 function? I would be very thankful.我将非常感谢。 I am beginner in programming我是编程初学者

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


}

Is my main function false?我的主要 function 是假的吗?

you need to overload ostream operator:您需要重载ostream运算符:

 friend std::ostream &operator<<(std::ostream &os, const Pair& pair) {
    os << pair.x << " " << pair.y << '\n';
    return os;
 }

If you are not comfortable with operator oveloading, you can simply print elements individually:如果您对操作员超载不满意,您可以简单地单独打印元素:

cout<< f.x <<" "<< f.y <<'\n';

The way you construct f , is wrong too ( int and Pair are not the same type).您构造f的方式也是错误的( intPair不是同一类型)。 You can try list initialization instead:您可以尝试 列表初始化

Pair f{2,3};
auto s = swap3(f);
cout<<f<<endl;
delete s;

Note that you have memory leak in your code, because your function returns a pointer, you don't store it and you never delete it.请注意,您的代码中有 memory 泄漏,因为您的 function 返回一个指针,您不存储它并且永远不会删除它。

I recommend using smart pointers to avoid memory leak you had:我建议使用智能指针来避免 memory 泄漏:

std::unique_ptr<Pair> swap3(const Pair& p){
    auto t = make_unique<Pair>(Pair{});
    t->x = p.y;
    t->y = p.x; 
    return t;
}

Live on Godbolt住在神螺栓

PS I am not sure what you want from swap, in the code you posted, you don't need a pointer at all. PS我不确定你想从交换中得到什么,在你发布的代码中,你根本不需要指针。 I think swap should be written like:我认为交换应该写成:

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

or:或者:

void swap3(Pair& p){
    Pair tmp{p.x, p.y};
    p.x = tmp.y;
    p.y = tmp.x;
}

Live on Godbolt住在神螺栓

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM