使用const unsigned**输入指针的C++快速排序

lh80um4z  于 2022-11-27  发布在  其他
关注(0)|答案(1)|浏览(93)

我目前正在努力与指针在C++中,特别是与以下函数的输入:

/*
... there is an immutable array a of unsigned integers that we are not allowed to change
In order to sort this array, a second array b containing pointers to the individual
elements in a is created. We then sort the poiners in b based on the values of the pointed-to elements in a.

(d) implement the quicksort function which sorts an array of pointers as outlined above.
    Note that the parameters to this function are two pointers, one to the first element in b and   
    one to the first element past the end of b.
 */
// Sort the range of pointers [begin; end)
void quicksort(const unsigned** begin, const unsigned** end)
{
    //TODO
}

然而,函数被赋予了常量值,那么有没有办法改变输入指针的位置呢?一个常见的Quicksort算法依赖于swap函数,我试着调用

void swap (const unsigned** a, const unsigned** b){
    const unsigned** temp = **a;
    **a = **b;
    **b = temp;
}

swap(begin, (end-1));

但是这不起作用,因为a的值不能改变(这里是b),因为它是常量。所以如果我不能改变它们的顺序,我怎么能对输入指针排序呢?

zi8p0yeb

zi8p0yeb1#

首先,我知道在刚开始使用c/c++的时候,这些东西确实很棘手,而且我也有过相当多的困惑。因此,我将尽我所能用最好的方式解释它:
在交换函数中,你要做的是,通过两次解引用和重新赋值来改变指针后面的整数的实际值,你得到了一个指针数组,它基本上是指向第一个指针的指针,如果你解引用两次,你会得到实际的整数,但是你不想这样,因为这个整数是常数.
相反,你希望在指针指向实际整数的位置结束,并交换这些整数。你可以通过一次解引用来实现这一点。如果你试图重新分配指针来改变它所指向的内容,你可以在不触及实际整数的情况下改变指针数组的顺序。
您交换函数应该如下所示:

void swap(const unsigned int** a,const unsigned int** b) {
    const unsigned int* temp = *a;
    *a = *b;
    *b = temp;
}

调用它的代码如下所示:

const unsigned int sort_without_touching[] = { 1 , 2 };

const unsigned int* ptr_array[] = {&sort_without_touching[0],
    &sort_without_touching[1]};

//1 2
std::cout << *ptr_array[0] << " " << *ptr_array[1] << std::endl;

swap((ptr_array+ 0), (ptr_array+ 1));

//2 1
std::cout << *ptr_array[0] << " " << *ptr_array[1] << std::endl;

相关问题