「std::swap」の版間の差分

提供: C++入門
移動: 案内検索
(Daemon がページ「Std::swap」を「std::swap」に移動しました)
(相違点なし)

2013年3月23日 (土) 16:30時点における版


読み方

std::swap
えすてぃーでぃー すわっぷ

概要

std::swap は、2つのオブジェクトの値を交換します。

たとえば、こういったコードをわざわざ書くことはありません。

int a = 0, b = 100, t;
t = a;
a = b;
b = t;

上記は、こうなります。

int a = 0, b = 100;
std::swap(a,b);


std::swapのシンプルな例

ソースコード std_swap.cpp

#include <iostream>     // std::cout
#include <utility>      // std::swap
 
int
main(int argc, char *argv[]) {
 
        int     x = 10, y = 20;
        std::swap (x, y);
        std::cout
                << "x=" << x
                << " y=" << y
                << std::endl;
        return 0;
}

コンパイル

g++  std_swap.cpp -o std_swap

実行例

% ./std_swap
x=20 y=10

配列を swap する例

ソースコード std_swap_2.cpp

#include <iostream>     // std::cout
#include <utility>      // std::swap
 
int
main(int argc, char *argv[]) {
 
        int     foo[4]; // ? ? ? ?
        int     bar[] = {10,20,30,40};
        std::swap (foo, bar);
        // foo: 10 20 30 40
        // bar: ?  ?  ?  ?
 
        for ( int i: foo ) {
                std::cout << ' ' << i;
        }
 
        std::cout << std::endl;
        return 0;
}

コンパイル

g++48 -std=c++11  std_swap_2.cpp -o std_swap_2

実行例

% ./std_swap_2
 10 20 30 40


関連項目