希望我能对我做的排序方法有所建议。
这段代码的目的是创建一个int指针数组,并根据常规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;
}
我认为实际上可能有人需要以理智的方式对指针数组进行排序:
#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;
}
丑陋的中间循环可以完全替换为超过pped范围的zip
范围,但是我现在没有自己的带有引用语义的实现,而且我懒得检查Boost 1。1个
另外,因为我认为我们应该一遍又一遍地重复这一过程,直到新手理解它为止:
1实际上,这对于确保两个范围(在这种情况下为两个数组)具有相同的长度非常重要。不同的压缩约定要么要求范围的长度相同(否则会崩溃或抛出),或者如果其中一个范围太短则填充空白数据。尽管在这样一个简单的程序中看起来很明显,但在实际代码中要小心。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句