PeterNaut's blog

By PeterNaut, 11 years ago, In English

In order to swap two arrays in O(1) you can do this using pointers:

#include <algorithm>
int AA[100], *A=AA, BB[100], *B=BB;
swap(A, B);

But how can you do that for matrixes in C++?

Tags c++
  • Vote: I like it
  • -18
  • Vote: I do not like it

»
11 years ago, # |
Rev. 5   Vote: I like it 0 Vote: I do not like it

First, you do not need to make *A and *B. swap (AA,BB) will do.

Second, matrices are just arrays too so they can be swapped too in constant time. (even if array elements are dynamically created using new keyword).

Lastly, if you still do not believe something; vectors make it more convenient

»
11 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You do it the same way:

int AA[100][100], (*A)[100]=AA, BB[100][100], (*B)[100]=BB;    
swap(A, B);

int (*)[100] is a pointer to an array of 100 ints. It may be easier to define a struct containing the array, and use pointers to such objects.

  • »
    »
    11 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks! But why do you need the paranthesis in (*A)[100]=AA?

    • »
      »
      »
      11 years ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      int (*A)[100] is a pointer to an array of 100 ints. int *A[100] is an array of 100 pointers to ints. You can google for "c declaratons" for more reading.