用C++排序指针数组

Con*_*nor 3 c++ arrays sorting algorithm pointers

希望我能就我制作的排序方法得到一些建议.

此代码的目的是创建一个int指针数组,并通过regular int数组的内容对该数组中的指针进行排序.然后根据原始int数组的位置为不同的变量赋值.

我在使用这段代码时遇到的奇怪之处在于测试代码在我知道的情况下不应该影响任何东西......实际上是影响了我指针的内容.也许值不会改变,但我编写测试代码的方式会导致错误.

 //create array
 int c[8] = {3,1,5,7,8,2,6,4};
 //create pointer array
 int *newptr[8];
 for(int k = 0; k<8; k++)
 {
     newptr[k] = &c[k];
 }
//sort pointer array
for(int j = 0; j<8; j++)
{
    for(; j > -1 && *newptr[j] < *newptr[j+1]; j--)
    {
        int *temp = newptr[j+1];
        newptr[j+1] = newptr[j];
        newptr[j] = temp;
    }
}
//set lookuplocation
int lookuplocation;
for(int i = 0; i<8; i++)
{
    cout << *newptr[i];

    if(newptr[i] == &c[0])
    {
        cout << *newptr[i] << endl;

        //If I use endl or \n to test the pointers values I end up with only
        //a part of the correct data. 

        cout << "\nSuccess!\n";
        lookuplocation = 0;
    }
}
//Also for my last test sometimes the first element gets messed up as well
//test arrays
for(int k = 0; k<8; k++)
{
    cout << "Element " << k << ": " << *newptr[k] << endl;
    cout << "Element " << k << ": " << newptr[k] << endl;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*icz 9

我想有人可能真的需要以理智的方式对指针数组进行排序:

#include <iostream>
#include <array>
#include <algorithm>

int main() {
    std::array<int, 8> arr { 3, 5, 4, 1, 2, 7, 6, 8 };
    std::array<int*, 8> p_arr;

    for (unsigned i = 0; i < 8; ++i) {
        p_arr[i] = &arr[i];
    }

    std::sort(p_arr.begin(), p_arr.end(), [](int* a, int* b) { return *a < *b; });

    for (auto i : p_arr) 
        std::cout << *i;
}
Run Code Online (Sandbox Code Playgroud)

对于超重范围,丑陋的中间循环完全可以替换zip范围,但我现在没有自己的参考语义实现,而且我懒得检查Boost.1

这是Coliru的现场样本.

另外,因为我认为我们应该一遍又一遍地重复这一点,直到新手了解它:

  • 不要重新发明分拣轮(除非它是玩具实施)
  • 尽可能避免在C++中使用指针.

1这对于确保两个范围(在这种情况下是两个数组)具有相同的长度实际上很重要.不同的压缩约定要求范围具有相同的长度(否则崩溃或抛出)或者如果其中一个范围太短则填充空数据.虽然在这样一个简单的程序中看似显而易见,但在现实世界的代码中要小心.