Re: "Swapping" two arrays like this doesn't compile because..
Eric Lilja wrote:
..during the call to swap_arrays the name of the array decays to a
pointer to its first element and that pointer is a temporary variable
and you cant bind a non-const reference to a temporary. Correct
analysis?
I don't think so.
The code (that only compiles if you comment out the call to
swap_arrays()):
#include <iostream>
#include <iterator>
using namespace std;
void swap_arrays(int *&a1, int *&a2)
{
int *ptr = a1;
a1 = a2;
a2 = ptr;
}
That function will not swap arrays. It swaps objects of type pointer-to-int.
int main()
{
int array1[] = {1, 2, 3};
int array2[] = {4, 5, 6};
swap_arrays(array1[0], array2[0]);
You promised int*& as the parameter. What you pass is int&.
cout << "array1 after swap:" << endl;
copy(array1, array1 + sizeof(array1) / sizeof(array1[0]),
ostream_iterator<int>(cout, " "));
cout << endl << "array2 after swap:" << endl;
copy(array2, array2 + sizeof(array2) / sizeof(array2[0]),
ostream_iterator<int>(cout, " "));
cout << endl;
}
Try this:
#include <cstddef>
#include <algorithm>
using namespace std;
template < typename T, std::size_t N >
void swap ( T (&lhs) [N], T (&rhs) [N] ) {
for ( std::size_t i = 0; i < N; ++i ) {
swap( lhs[i], rhs[i] );
}
}
#include <iostream>
#include <iterator>
using namespace std;
int main ( void ) {
int array1[] = {1, 2, 3};
int array2[] = {4, 5, 6};
swap( array1, array2 );
cout << "array1 after swap:" << endl;
copy(array1, array1 + sizeof(array1) / sizeof(array1[0]),
ostream_iterator<int>(cout, " "));
cout << endl << "array2 after swap:" << endl;
copy(array2, array2 + sizeof(array2) / sizeof(array2[0]),
ostream_iterator<int>(cout, " "));
cout << endl;
}
Best
Kai-Uwe Bux