tags:

views:

104

answers:

2

My question is as follows:

Refer to the following array declaration in the main():

const int size = 4;
int x[size][size] = {{1, 2, 3, 4}, {5, 6, 7, 8},
  {9, 8, 7, 3}, {2, 1, 7, 1}};

Write a function SwapRows() to swap two rows of the above 2D array. For example, if the function has been called to swap the first and the second rows of the above 2D array then the result would be that the first row now becomes {5, 6, 7, 8} and the second row now becomes {1, 2, 3, 4}. The function receives as parameter the 2D array, the size of the array, and two integers to indicate the rows to swap.

Help,,how can i go about this????? Note: Using C++ Language

+4  A: 

Pseudo code:

SwapRows(x[size][size], row0, row1, size)
  for col = 0 to size - 1 do
    temp = x[row0][col]
    x[row0][col] = x[row1][col]
    x[row1][col] = temp

Now all you need to do is convert the pseudo code into C++, then test, debug and document it.

Paul R
A: 
#include <algorithm>

void SwapRows(int arr[][4], int r1, int r2)
{
    std::swap(arr[r1],arr[r2]);
}
PigBen
maybe pass arr[][4] via reference?
portland
@portland Why? It's an array, it's already passed by reference.
PigBen
For homework problems it's generally accepted that you should only provide hints and general guidance, not complete solutions.
Paul R
To be used with `std::swap`, doesn't the type have to be _Assignable_ which `int[4]` is not?
Charles Bailey
(I'm assuming C++03 as you are getting `swap` from `<algorithm>` and not `<utility>` which would be C++0x which _does_ have a specialization of `swap` for arrays.)
Charles Bailey
@Paul R: It's one line of code, what hints would I provide? Whether it's homework or not is irrelevant to me. I don't care if he fails his classes because he doesn't learn how to program. The question is tagged C++. I'm answering a question about C++. This is how you solve his problem in C++. :)
PigBen
But is it correct C++?
Charles Bailey
@Charles: I don't know, is it? It compiles in MSVC++, and it compiles in GCC. Does anything else matter? Not really.
PigBen
@PigBen: Perhaps not to you. Are you intentionally using C++0x?
Charles Bailey
@Charles: I'm intentionally using code that works in compilers that I care about. I don't know where to get information on which functions are available in which headers in C++0x. I usually use cplusplus.com for reference, but it isn't updated for 0x. All I know is that when I include <algorithm>, it works, in both VC++ and GCC. If I include <utility>, but not <algorithm>, it works in GCC, but not VC++.
PigBen