1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <iostream>
#include <valarray>
#include <algorithm>
#include <numeric>
using namespace std;
template<typename T> void swapDiagonals( valarray<T> &A, int N )
{
auto diag1 = slice(0,N,N+1), diag2 = slice(N-1,N,N-1);
valarray<T> temp = A[diag1];
A[diag1] = A[diag2];
A[diag2] = temp;
}
template<typename T> void print( const valarray<T> A, int N )
{
int i = 0;
for ( T e : A ) { cout << e << '\t'; if ( !((++i) % N) ) cout << '\n'; }
cout << '\n';
}
int main()
{
int N = 4;
valarray<int> A(N*N);
iota( begin(A), end(A), 1 );
print( A, N );
swapDiagonals( A, N );
print( A, N );
N = 5;
valarray<char> B(N*N);
iota( begin(B), end(B), 'a' );
print( B, N );
swapDiagonals( B, N );
print( B, N );
}
| |