简体   繁体   English

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. 不幸的是,指针只是我的大脑似乎不理解的那些概念之一。

Here's the call: 这是电话:

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? 它是否也在调整/比较其指向的值,还是在比较实际的指针本身?

Any help is appreciated. 任何帮助表示赞赏。 Cheers. 干杯。

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). 将它们视为对值的引用,而不是值本身(这是邮箱的地址,而不是邮箱的内容),可能会有所帮助。

In your code 'int* min = i;' 在您的代码中'int * min = i;' sets min to the same address (reference) as 'i'. 将min设置为与“ i”相同的地址(引用)。 So later in your 'if' statement 'if (j < min)' you are comparing references, not values. 因此,稍后在“ if”语句“ if(j <min)”中,您将比较引用而不是值。 You need to "dereference" your pointer to get at the values, like this: 'if (*j < *min)'. 您需要“取消引用”指针以获取值,例如:'if(* j <* min)'。

In pointers if, 如果是指针,

int* i; //i holds actual physical memory address & i* holds value at that address.

Now, in your selectionSort functions if condition you are comparing actual memory addresses and not values. 现在,在您的selectionSort函数中, if条件比较实际内存地址而不是值。 See example here. 请参阅此处的示例。

You should never really be put in a position that you need to create your own sort algorithm. 绝对不要把自己摆在需要创建自己的排序算法的位置。 Instead, you should always try to utilize existing collection class, eg set, which will sort for you. 相反,您应该始终尝试利用现有的收集类,例如set,它将为您排序。 That being said, if your goal is to better understand pointers, then as greatwolf commented, you shouldn't be sorting pointers, but what they are pointing to! 话虽如此,如果您的目标是更好地理解指针,那么正如greatwolf所评论的那样,您不应该对指针进行排序,而应该对指针进行排序! In your case integers. 在您的情况下,整数。

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

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