change the data of 2 rows of an array

How can I change the data of 2 rows of an array using the swap.
I write the basic change code but i want to improve performance by changing it into one line (using swap function or something like that as in the bottom of this page).
my main code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int i,j;
int A[50][4];
i=5;
j=21;

int t1 = A[j][0];
int t2 = A[j][1];
int t3 = A[j][2];
int t4 = A[j][3];

A[j][0]=A[i][0]  ;
A[j][1]=A[i][1]  ;
A[j][2]=A[i][2] ;
A[j][3]=A[i][3] ;

A[i][0] = t1;
A[i][1] = t2;
A[i][2] = t3;
A[i][3] = t4;


	

What I want to change:
change line 6-18 in to one of the following:
A[i][] = A[j][];
or
swap (A[i] , A[j])
Last edited on
Assuming you know the size of the array dimensions at compile-time and you want to swap the first two rows (only an example), you could use

1
2
3
4
5
6
 
void swapRows(int (&iArr)[3][3])
{
    for (int i = 0; i < 3; ++i)
          std::swap(iArr[0][i], iArr[1][i]);
}


Notice that &iArr[3][3] is array of references, so you need the parentheses around the name of the array.
Last edited on
A more general version

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
41
42
43
44
45
46
47
 
#include <iostream>


#define ROWS 3
#define COLS 3


void swapRows(int (*iArr)[COLS], int row1, int row2)
{
    for (int i = 0; i < COLS; ++i)
          std::swap(iArr[row1 - 1][i], iArr[row2 - 1][i]);
}


void output2DArray(int iArr[][COLS])
{
    for (int i = 0; i < ROWS; ++i)
    {
        for (int j = 0; j < COLS; ++j)
        {
            std::cout << " " << iArr[i][j];
        }

        std::cout << std::endl;
    }
}


int main()
{
    int iArr[][3] = {1, 2, 3,
                     4, 5, 6,
                     7, 8, 9};

    std::cout << "Before SWAP..." << std::endl;

    output2DArray(iArr);

    swapRows(iArr, 1, 3);

    std::cout << "After SWAP..." << std::endl;

    output2DArray(iArr);

    return 0;
}
1
2
    for (int i = 0; i < COLS; ++i)
          std::swap(iArr[row1 - 1][i], iArr[row2 - 1][i]);
that's just std::swap(iArr[row1 - 1], iArr[row2 - 1]); these days
Topic archived. No new replies allowed.