使用指针交换结构 [英] Swapping structures using pointers

查看:101
本文介绍了使用指针交换结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们具有如下结构:

Suppose we have a structure like the following:

struct EMPLOYEE{

   int EmpID;
   int Sal;

} Stu[5];

如果满足以下条件,我们希望交换这些结构:

And we wish to swap these structures if the following condition is true:

Stu[i].Sal < Stu[0].Sal

一种方法是交换整个结构.像这样:

One way way could be by swapping the whole stucture. Something like this:

TempStu.Sal = Stu[i].Sal;
Stu[i].Sal = Stu[0].Sal;
Stu[0].Sal = TempStu.Sal;

TempStu.EmpID = Stu[i].EmpID;
Stu[i].EmpID = Stu[0].EmpID;
Stu[0].EmpID = Temp.Stu.EmpID;

这使其成为非常耗时的方法. 其他方法可能是使用指向EMPLOYEE结构的指针数组,然后仅对这些指针进行排序.我不知道该怎么做.

This makes it a very time consuming method. Other method could be using an array of pointers to EMPLOYEE structs and then sort these pointers only. I'm unable to figure out how to do the this.

这是我的起点.

EMPLOYEE *St[5];

for(int j=0; j<5; j++) {

   St[j] = &Stu[j];

}

if(Stu[i].Sal < Stu[0].Sal) 
   swap(St[i],St[0]);

void swap(EMPLOYEE *A, EMPLOYEE *B) {

    EMPLOYEE temp = *A;
    *A = *B;
    *B = temp;
}

这是正确的方法吗?

推荐答案

这是正确的方法吗?

Is this a correct approach?

差不多.在swap()中,您需要使用指向指针的指针(或C ++中指向指针的引用).否则,您对AB所做的更改不会传播回调用方.

Almost. In swap(), you need to use pointers to pointers (or references to pointers in C++). Otherwise the changes you make to A and B don't propagate back to the caller.

这篇关于使用指针交换结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆