🌍 C++ Study/C++ 기초
C++ string 문자열 뒤집기 std::reverse
맨텀
2024. 11. 16. 16:51
std::reverse
cplusplus : reverse
https://cplusplus.com/reference/algorithm/reverse/
std::reverse는 <algorithm> 헤더에 포함되어있으며,
시작과 끝 이터레이터를 받는다.
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last);
문자 전체를 뒤집고 싶다면 string에서 제공하는 begin()과 end()를 넣어주면 된다.
std::reverse(text.begin(), text.end()); // 문자열 뒤집기
주의할 점은 end() 는 마지막 위치가 아니라 마지막 문자 다음 위치라는 점.
인덱스 from 부터 end 까지를 뒤집고 싶다면 다음과 같이 +1을 해줘야한다.
std::reverse(my_string.begin() + from, my_string.begin() + end + 1);
2. 직접 뒤집기
stl 알고리즘을 사용하지 않고 직접 뒤집고 싶다면 std::swap 을 사용하면 된다.
#include <iostream>
#include <string>
int main() {
std::string text = "abcdef";
int n = text.length();
// 문자열의 앞뒤를 교환
for (int i = 0; i < n / 2; ++i) {
std::swap(text[i], text[n - i - 1]);
}
std::cout << "Reversed: " << text << std::endl;
return 0;
}