希望我能得到一些关于我所做的分类方法的建议。
此代码的目的是创建一个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;
}发布于 2013-08-05 08:07:13
如果数组c[n]的范围为1 ..n,您可以使用以下算法,该算法在O(n)时间复杂度中工作:
for(int j = 0; j < n; j++)
while(*newptr[*newptr[j] - 1] != *newptr[j])
std::swap(newptr[*newptr[j] - 1], newptr[j]);其背后的想法是将值1赋值给指针newptr[0],2赋给指针newptr[1],.和n给指针newptr[n-1]。没有比这更有效的算法(特别是在C++11中,因为std::swap将使用std::move)。
因此,对于int c[8] = {3,1,5,7,8,2,6,4},您可以得到(忽略对值表的引用):
1233 成功! 45678
更新:,如果您想要相反的顺序:
for(int j = 0; j < n; j++)
while(*newptr[n - *newptr[j]] != *newptr[j])
std::swap(newptr[n - *newptr[j]], newptr[j]);对于int c[8] = {3,1,5,7,8,2,6,4},您可以得到:
8765433 成功! 21
发布于 2013-08-05 11:36:10
流行的方法是实现使用给定比较器对元素排序的泛型sort函数,这样就可以对数组元素进行抽象。有几种方法:
template<typename ElementType, typename CompType>
void sort(ElementType array[], size_t size, CompType cmp);
template<typename ElementType, typename CompType>
void sort(std::vector<ElementType> & array, CompType cmp);
template<typename IteratorType, typename CompType>
void sort(IteratorType first, IteratorType last, CompType cmp);最后一种方式更可取,因为您也可以对容器类型进行抽象。
发布于 2013-08-05 07:13:46
首先要改变这一点:
for(; j > -1 && *newptr[j] < *newptr[j+1]; j--)
转到
for(int i=j; i > -1 && *newptr[i] < *newptr[i+1]; i--)
似乎更有效率..。
https://stackoverflow.com/questions/18052204
复制相似问题