繁体   English   中英

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

[英]C++ quicksort with const unsigned** input pointers

我目前正在努力处理 C++ 中的指针,尤其是以下 function 的输入:

/*
... 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
}

然而, Function 被赋予了常量值,那么有什么办法可以改变输入指针的 position 吗? 一种常见的快速排序算法依赖于交换 function,我尝试调用

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

swap(begin, (end-1));

在 Quicksort Function 中。但这不起作用,因为 **a 的值无法更改(此处,值为 **b),因为它是常量。 那么,如果我不能更改它们的顺序,我什至如何能够对输入指针进行排序呢?

首先,我知道在开始使用 c/c++ 时这些东西真的很棘手,而且当我这样做的时候我也有相当多的困惑。 因此,我将尽我所能来解释它:

您在交换 function 中尝试做的是通过取消引用两次并重新分配来更改指针后面整数的实际值。 你得到了一个指针数组,它基本上是一个指向第一个指针的指针,如果你两次取消引用它,你最终会得到实际的整数,但是你不希望这样,因为这个 integer 是常量。

相反,您想以指向实际整数的指针结束并交换它们。 您可以通过仅取消引用一次来实现。 如果您尝试重新分配指针以更改它指向的内容,则可以更改指针数组的顺序,而无需触及实际的整数。

你的交换 function 应该是这样的:

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;

暂无
暂无

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

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