swap を使ってみる (C++)
C++
Published: 2020-04-04

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

swap は、

2つの値を入れ替える。

使ってみます。

test.cpp

#include <bits/stdc++.h>
// #define NDEBUG
#include <cassert>
using namespace std;

int main() {
    int x = 100, y = 777;
    cout << "case1" << endl;
    printf("x: %d y: %d\n", x, y);

    cout << "case2" << endl;
    swap(x, y);
    printf("x: %d y: %d\n", x, y);

    cout << "end" << endl;
}

出力結果

case1
x: 100 y: 777
case2
x: 777 y: 100
end

参考