C++
[C++] 뒤집는 함수 : reverse()
kugnuoy
2024. 3. 1. 22:44
reverse()는 STL 지원 함수로 문자열, 배열, 벡터 모두 뒤집을 수 있다.
반환형이 없고 string 메서드가 아니므로 reverse(시작주소, 끝주소) 와 같이 사용한다. (A.reverse() X)
1. 문자열
string A = "abcde";
reverse(A.begin(), A.end());
cout << A;
[출력]
edcba
2. 배열
int a[3] = {1,2,3};
reverse(a, a+3);
for (int i:a) cout << i;
[출력]
321
3. 벡터
vector<int> a = {1,2,3};
reverse(a.begin(), a.end());
for (int i:a) cout << i;
[출력]
321
https://cplusplus.com/reference/algorithm/reverse/
https://cplusplus.com/reference/algorithm/reverse/
12345678 template void reverse (BidirectionalIterator first, BidirectionalIterator last) { while ((first!=last)&&(first!=--last)) { std::iter_swap (first,last); ++first; } }
cplusplus.com