我有一个函数需要一个指针数组:
void SortResistance(MyClass ** pointerArray, int arraySize);
并进行冒泡排序。在该函数中,我可以使用以下方法访问任意两个数组元素:
MyClass * item1 = *pointerArray + i;
MyClass * item2 = *pointerArray + i + 1;
我在哪里迭代数组。到目前为止,一切都很好。当我使用非常简单的交换函数交换值时,例如:
void Swap(MyClass ** item1, MyClass ** item2);
指针上的值按预期交换。
我的问题是我不知道如何将它们重新分配回pointerArray。
这不起作用:
*(pointerArray + i) = item1;
*(pointerArray + i + 1) = item2;
(好吧,它在 i 等于 0 时起作用,否则它只会移动指针,而不是它的值。)
我想知道是否有人可以帮我解决这个问题。函数原型无法更改,因此我假设它们是正确的。
这是最简单的实现中的血淋淋的细节。非常感谢您的回复。
我被要求查看类似于以下声明的内容并实施:
#include <string>
using namespace std;
void main()
{
//TODO: instantiate an array of pointers and sort them using the below
};
class MyClass
{
public:
double value;
string name;
}
void Sort(MyClass ** myArray, int arraySize)
{
//TODO: implement bubble sort
}
void Swap(MyClass ** pointer1, MyClass ** pointer2)
{
MyClass *temp = *pointer1;
*pointer1 = *pointer2;
*pointer2 = temp;
}
我的解决方案,基于类似以下http://www.cplusplus.com/reference/algorithm/sort/将是这样的:
#include <string>
using namespace std;
class MyClass
{
public:
double value;
string name;
};
void Swap(MyClass ** pointer1, MyClass ** pointer2)
{
MyClass *temp = *pointer1;
*pointer1 = *pointer2;
*pointer2 = temp;
}
void Sort(MyClass ** myArray, int arraySize)
{
bool done = false; // this flag will be used to check whether we have to continue the algorithm
while (!done)
{
done = true; // assume that the array is currently sorted
for (int i = 0; i < arraySize - 1; i++) // for every element in the array
{
MyClass * p1 = *myArray + i;
MyClass * p2 = *myArray + i + 1;
//MyClass * p1 = *(myArray + i);
//MyClass * p2 = *(myArray + i + 1);
//MyClass * p1 = myArray[i];
//MyClass * p2 = myArray[i + 1];
if ( p1->value > p2->value ) // compare the current element with the following one
{
// They are in the wrong order, swap them
Swap(&p1, &p2);
//Swap(*(&myArray + i), *(&myArray + i + 1));
//Swap(myArray + i, myArray + i + 1);
*(myArray + i) = p1;
*(myArray + i + 1) = p2;
done = false; // since we performed a swap, the array needs to be checked to see if it is sorted
// this is done in the next iteration of the while
}
}
}
}
void main()
{
MyClass item1; item1.name = "item1"; item1.value = 25.5;
MyClass item2; item2.name = "item2"; item2.value = 15.5;
MyClass myItems[2]; myItems[0] = item1; myItems[1] = item2;
MyClass * myPointerToItemArray = myItems;
Sort(&myPointerToItemArray, 2);
}
代码在 VS 2010 下编译得很好。如您所见,一切都很顺利,直到我必须将新的一组指针重新分配给数组。任何建议将不胜感激。我开始认为必须修改声明才能使其工作。