Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ swapping array elements by moving, not copying

Tags:

c++

arrays

Is it possible to swap two elements of an array by simply moving both to the new index instead of a costly copy with a temp value?

I have this code:

struct Piece {
    int index;
    int type;
    int square;

    Piece() {}
    ~Piece() {}
    Piece(Piece& piece) {
        printf("copy");
    }
    Piece(Piece&& piece) {
        printf("move");
    }

    void operator=(Piece& piece) {
        printf("copy1");
        int temp = square;
        square = piece.square;
        piece.square = temp;
    }
    void operator=(Piece&& piece) {
        printf("move1");
    }
};

int main() {
    Piece* pieces = new Piece[10];
    Piece* sliders = new Piece[10];

    pieces[0] = {};
    pieces[0].square = 50;
    pieces[1] = {};
    pieces[1].square = 20;

    Piece temp = pieces[0];
    pieces[0] = pieces[1];
    pieces[1] = temp;

    cout << pieces[1].square << " " << pieces[0].square;
    char test;
    cin >> test;
}

This always prints "move" when initializing and "copy1" when swapping with temp. Is there any way to do the same by moving, without using an array of pointers?

Please ignore the bad style of this code.

like image 761
zuokuok Avatar asked Dec 06 '25 06:12

zuokuok


2 Answers

Use std::swap...

std::swap(pieces[0], pieces[1]);

You could equivalently write:

Piece temp = std::move(pieces[0]);
pieces[0] = std::move(pieces[1]);
pieces[1] = std::move(temp);

but std::swap is more concise.

like image 70
Brian Bi Avatar answered Dec 07 '25 20:12

Brian Bi


Option 1: Use std::swap.

std::swap<Piece>(pieces[0], pieces[1])

Option 2: Use std::move.

Piece temp = std::move(pieces[0]);
pieces[0] = std::move(pieces[1]);
pieces[1] = std::move(temp);

Moreover, make your move operations non throwing.

like image 35
szulak Avatar answered Dec 07 '25 19:12

szulak