'C++' std::swap

토스트·2025년 5월 2일

'C++' std::algorithm

목록 보기
10/11

<utility>
<string_view>

swap

template<class T>
void swap(T& a, T& b); // 조건부로 noexcept since C++11, constexpr since C++20

template<class T2, std::size_t N>
void swap(T2 (&a)[N], T2 (&b)[N]); // 조건부로 noexcept since C++11, constexpr since C++20

: 주어진 값을 서로 교환합니다.

  • a, b : 교환할 값

<example>

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> vec1 = { 10, 15, 5, 2, 4 };
    vector<int> vec2 = { 5, 7, 9, 11, 13 };

    swap(vec1, vec2);

    for (const int& num : vec1) {
        cout << num << ' ';
    }

    cout << endl;

    for (const int& num : vec2) {
        cout << num << ' ';
    }

    cout << endl;

    swap(vec1[0], vec1[1]);

    cout << vec1[0] << ", " << vec1[1];

    return 0;
}

결과값

0개의 댓글