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]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…