Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

c++ - Should I reference elements of arrays when working with them?

Let's say we want to implement bubble sort using the following code:

void bubbleSort(int arr[], int n){
    for(int i=0; i<n-1; i++){
        for(int j=i+1; j<n;j++){
            if(arr[i]>arr[j]){
                swap(arr[i], arr[j]);
            }
        }
    }
}

Should there be an & before arr[i] and arr[j] in the swap function and what would be the difference? I remember having read somewhere that one doesn't need to put the & sign before array elements in order to work with the adresses directly. I know this is a stupid question, so excuse me for asking, but such little details help me understand pointers better.

question from:https://stackoverflow.com/questions/66048513/should-i-reference-elements-of-arrays-when-working-with-them

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Should there be an & before arr[i] and arr[j] in the swap function

Depends on the types of the arguments that swap accepts.

If you're asking about std::swap of the C++ standard library, then: No, there shouldn't be operator &.

and what would be the difference?

The unary & operator is the addressof operator. The result is a prvalue pointer which points to the operand.

The arguments of std::swap are references to non-const, and therefore cannot be bound to rvalue arguments. Besides, that would be swapping pointers; not the values of the elements.

You could do std::iter_swap(&arr[i], &arr[j]) because std::iter_swap indirects through the argument iterators and swaps the pointed objects... but that would be unnecessarily complicated. I don't recommend it for this case.

Alternatively, std::iter_swap(arr + i, arr + j) would also work.


Some examples:

// similar to std::swap
void swap1(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

swap1(arr[i], arr[j]);

// similar to std::iter_swap
void swap2(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

swap2(arr + i, arr + j);
swap2(&arr[i], &arr[j]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...