问题
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;
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.
Here is a start I made..
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?
回答1:
Is this a correct approach?
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.
回答2:
Your idea is correct, but your only swapping two local pointers in your function.
try this
if(Stu[i].Sal < Stu[0].Sal)
swap(&St[i],&St[0]);//pass the addresses
void swap(EMPLOYEE **A, EMPLOYEE **B) {
EMPLOYEE *temp = *A;
*A = *B;
*B = temp;
}
回答3:
Try this:
void swap(EMPLOYEE* arr[],int i,int j)
{
EMPLOYEE* temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
if (Stu[i].Sal < Stu[0].Sal)
swap(Stu,i,0);
回答4:
If you use array, you can swap struct through each field you can not use pointer. because the nature of the array is a series of consecutive memory cells. You only change the value inside the pointer but not swap the position of the struct.
-
You should use the linked list. Because its locations are dynamic, you can swap its
来源:https://stackoverflow.com/questions/21968548/swapping-structures-using-pointers