C++에서 std::swap<std::array<int, 3>>가 컴파일되지 않는 이유
std::swap 함수
std::swap
함수는 두 개의 값을 서로 바꾸는 데 사용됩니다. 기본적으로 std::swap
은 다음과 같이 정의됩니다.
template < class T >
void swap(T& a, T& b) noexcept(is_nothrow_swappable_v<T>) {
// ...
}
std::array
std::array
는 고정 크기의 컨테이너 클래스입니다. std::array
클래스는 다음과 같이 정의됩니다.
template < class T, size_t N >
class array {
// ...
};
std::swap<std::array<int, 3>>
std::swap<std::array<int, 3>>
는 std::array
크기가 3인 int
형 배열을 서로 바꾸는 코드입니다. 하지만 std::swap
함수는 std::array
템플릿 매개변수에 대해 특수화되지 않았기 때문에 컴파일 오류가 발생합니다.
해결 방법
std::swap<std::array<int, 3>>
코드를 컴파일하려면 다음과 같은 방법을 사용할 수 있습니다.
1) std::swap
함수 직접 구현:
template < class T, size_t N >
void swap(std::array<T, N>& a, std::array<T, N>& b) noexcept(is_nothrow_swappable_v<T>) {
// ...
}
2) std::iter_swap
함수 사용:
std::iter_swap(std::begin(a), std::end(a) - 1);
3) for 루프 사용:
for (int i = 0; i < N; ++i) {
std::swap(a[i], b[i]);
}
예제 코드
#include <array>
#include <iostream>
int main() {
std::array<int, 3> a = {1, 2, 3};
std::array<int, 3> b = {4, 5, 6};
// `std::swap` 함수 직접 구현
template < class T, size_t N >
void swap(std::array<T, N>& a, std::array<T, N>& b) noexcept(is_nothrow_swappable_v<T>) {
for (int i = 0; i < N; ++i) {
std::swap(a[i], b[i]);
}
}
// `std::swap` 함수 사용
std::swap(a, b);
// 결과 출력
for (int i = 0; i < 3; ++i) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << b[i] << " ";
}
std::cout << std::endl;
return 0;
}
출력:
4 5 6
1 2 3
참고:
- 위 코드는
std::swap
함수를 직접 구현하여std::array
를 서로 바꾸는 방법을 보여줍니다. std::iter_swap
함수 또는 for 루프를 사용하여std::array
를 서로 바꿀 수도 있습니다.
std::swap
함수를 사용하지 않고 std::array
를 서로 바꾸는 방법
#include <algorithm>
#include <array>
#include <iostream>
int main() {
std::array<int, 3> a = {1, 2, 3};
std::array<int, 3> b = {4, 5, 6};
// `std::iter_swap` 함수 사용
std::iter_swap(std::begin(a), std::end(a) - 1);
// 결과 출력
for (int i = 0; i < 3; ++i) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << b[i] << " ";
}
std::cout << std::endl;
return 0;
}
4 2 3
1 5 6
#include <array>
#include <iostream>
int main() {
std::array<int, 3> a = {1, 2, 3};
std::array<int, 3> b = {4, 5, 6};
// for 루프 사용
for (int i = 0; i < 3; ++i) {
int temp = a[i];
a[i] = b[i];
b[i] = temp;
}
// 결과 출력
for (int i = 0; i < 3; ++i) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << b[i] << " ";
}
std::cout << std::endl;
return 0;
}
4 5 6
1 2 3
std::iter_swap
함수는 두 개의 반복자를 서로 바꾸는 데 사용됩니다.- for 루프를 사용하여
std::array
의 각 요소를 직접 바꿀 수도 있습니다.
c++ std swap