Swap lines in matrix

hi, so the question says "move the bottom line to the top and all the other ones dowm"

so i'm assuming if i were to have:
1
2
3
4
5

i'd need it to be like:
5
1
2
3
4

the matrix is basically a 2d array and i have to enter it fom the console. i don't know how the swapping works but here's how the beginning of my code looks(sorry, i know that's not a lot, but im stuck). could you please help me?

*also, i think it's possible to not use a dynamic array, right?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
using namespace std;
int main() {

    int size;

    cout << "matrix size = ";
    cin >> size;

    int** arr = new int* [size];
    for (int i = 0; i < size; i++) 
    {
        arr[i] = new int[size];
        for (int j = 0; j < size; j++) 
        {

            cin >> arr[i][j]; 
Last edited on
well, if you set it up as **, one of the very few advantages you have is that each row is a pointer.
so you can swap rows entirely with one small movement.

that is
int * tmp = arr[0];
arr[0] = arr[5];
arr[5] = tmp;
or use std::swap for this.
fidarova is after a rotation.
Last edited on
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
38
39
40
#include <iostream>
#include <random>
using namespace std;

int main()
{
	auto rand {mt19937 {random_device {}()}};
	auto randNo {uniform_int_distribution<int> {0, 9}};

	int size;

	cout << "matrix size = ";
	cin >> size;

	int** arr = new int* [size];

	for (int i = 0; i < size; ++i) {
		arr[i] = new int[size];

		for (int j = 0; j < size; ++j)
			cout << (arr[i][j] = randNo(rand)) << " ";

		cout << "\n";
	}

	rotate(arr, arr + size - 1, arr + size);
	cout << '\n';

	for (int i = 0; i < size; ++i) {
		for (int j = 0; j < size; ++j)
			cout << arr[i][j] << ' ';

		cout << '\n';
	}

	for (int i = 0; i < size; ++i)
		delete[] arr[i];

	delete[] arr;
}



matrix size = 5
4 8 9 9 6
5 0 8 2 0
0 7 3 8 1
4 1 4 2 2
8 6 8 9 1

8 6 8 9 1
4 8 9 9 6
5 0 8 2 0
0 7 3 8 1
4 1 4 2 2


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <valarray>
using namespace std;

using matrix = valarray< valarray<double> >;

void print( const matrix &M )
{
   for ( const auto &row : M )
   {
      for ( auto e : row ) cout << e << '\t';
      cout << '\n';
   }
}

int main()
{
   matrix A = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
   print( A );   cout << '\n';
   
   A = A.cshift( -1 );
   print( A );
}

1	2	3	
4	5	6	
7	8	9	
10	11	12	

10	11	12	
1	2	3	
4	5	6	
7	8	9	
Last edited on
thank you soooo much for the 193934th time!)
Topic archived. No new replies allowed.