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;
}
'🌍 C++ Study > C++ 기초' 카테고리의 다른 글
C++ std::count string의 문자 갯수 세기 std::count_if (0) | 2024.11.19 |
---|---|
C++ vector sort 벡터 정렬 algorithm (0) | 2024.11.17 |
C++ string 부분 문자열 구하기 string::substr (0) | 2024.11.16 |
C++ 벡터에 연속된 숫자 채우기 std::iota (0) | 2024.11.15 |
C++ int 최대값 구하기 numeric_limits<int>::max() (0) | 2024.11.14 |