C ++使用指针来选择排序函数 [英] C++ Using pointers for selection sort function
问题描述
我有一个任务通过传递指针来编写一些排序函数。不幸的是,指针只是我的大脑似乎不理解的那些概念之一。
I've got a task to code some sorting function by passing pointers. Unfortunately, pointers are just one of those concepts my brain doesn't seem to comprehend.
这是调用:
int size = 10000;
int* data = new int[size];
//omitted code that populates array for the sake of space
selectionSort(data, data+size);
这是我对函数的不正确尝试:
And here's my incorrect attempt at the function:
void selectionSort(int* first, int* last) {
for (int* i = first; i < last-1; i++) {
int* min = i;
for (int* j = i+1; j < last; j++) {
if (j < min) {
min = j;
}
int* temp = i;
i = min;
min = temp;
}
}
}
我有麻烦弄清楚当我比较一个指针与另一个,或调整指针时会发生什么。是调整/比较它指向的值还是比较实际指针本身?
Basically, I'm having trouble figuring out what happens when I'm comparing one pointer with another, or adjusting a pointer. Is it adjusting/comparing the value it's pointing too or is it comparing the actual pointers themselves?
任何帮助。干杯。
推荐答案
指针有时是一个难以理解的概念。也许它会帮助把它们看作一个值的引用,而不是值本身(它是邮箱的地址,而不是邮箱的内容)。
Pointers are sometimes a difficult concept to grok. Perhaps it will help to think of them as a reference to a value, rather than the value itself (it's an address of the mailbox, not the contents of the mailbox).
在你的代码'int * min = i;'中设置min到同一地址(引用)为'i'。所以稍后在你的'if'语句if(j< min)'你比较引用,而不是值。你需要取消引用你的指针来获取值,像这样:'if(* j< * min)'。
In your code 'int* min = i;' sets min to the same address (reference) as 'i'. So later in your 'if' statement 'if (j < min)' you are comparing references, not values. You need to "dereference" your pointer to get at the values, like this: 'if (*j < *min)'.
这篇关于C ++使用指针来选择排序函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!