最終更新日時(UTC):
が更新

履歴 編集

function
<utility>

std::pair::swap(C++11)

void swap(pair& p) noexcept(see below);           // (1) C++11
constexpr void swap(pair& p) noexcept(see below); // (1) C++20

概要

他のpairオブジェクトと値を入れ替える

要件

first_typesecond_typeSwappableであること。

効果

swap(this->first, p.first);
swap(this->second, p.second);

戻り値

なし

例外

noexcept(swap(first, p.first)) && noexcept(swap(second, p.second))である場合、この関数は決して例外を送出しない

#include <iostream>
#include <utility>
#include <string>

template <class T1, class T2>
void print(const std::string& name, const std::pair<T1, T2>& p)
{
  std::cout << name << " : (" << p.first << "," << p.second << ")" << std::endl;
}

int main()
{
  std::pair<int, std::string> p1(1, "aaa");
  std::pair<int, std::string> p2(2, "bbb");

  p1.swap(p2);

  print("p1", p1);
  print("p2", p2);
}

出力

p1 : (2,bbb)
p2 : (1,aaa)

参照