basic_string_erase2
basic_string_erase2 (std::basic_string의 erase/erase_if 자유 함수)
이 페이지는 C++20부터 추가된 std::basic_string용 erase 및 erase_if 자유 함수에 대해 설명해요. 이 함수들은 문자열에서 특정 값이나 조건에 맞는 문자를 효율적으로 제거하고, 제거된 문자의 개수를 반환해요. 멤버 함수와 달리 컨테이너 외부에서 알고리즘과 함께 사용할 수 있어요.
출처: cppreference
본문
함수 정의
<string> 헤더에 정의되어 있어요.
| 정의 | (1) | (2) |
|---|---|---|
template < class CharT , class Traits , class Alloc , class U > constexpr std :: basic_string < CharT , Traits , Alloc >:: size_type erase ( std :: basic_string < CharT , Traits , Alloc >& c , const U & value ); |
(since C++20) (until C++26) | |
template < class CharT , class Traits , class Alloc , class U = CharT > constexpr std :: basic_string < CharT , Traits , Alloc >:: size_type erase ( std :: basic_string < CharT , Traits , Alloc >& c , const U & value ); |
(since C++26) | |
template < class CharT , class Traits , class Alloc , class Pred > constexpr std :: basic_string < CharT , Traits , Alloc >:: size_type erase_if ( std :: basic_string < CharT , Traits , Alloc >& c , Pred pred ); |
(since C++20) |
erase 함수는 다음과 같이 동작해요.
auto it = std::remove(c.begin(), c.end(), value);
auto r = c.end() - it;
c.erase(it, c.end());
return r;
erase_if 함수는 다음과 같이 동작해요.
auto it = std::remove_if(c.begin(), c.end(), pred);
auto r = c.end() - it;
c.erase(it, c.end());
return r;
매개변수
| 매개변수 | 설명 |
|---|---|
c |
문자를 제거할 컨테이너예요. |
value |
제거할 값이에요. |
pred |
요소를 제거해야 하는지 판단하는 단항 술어예요. pred(v) 표현식은 (const) CharT 타입의 모든 인수 v에 대해 bool로 변환 가능해야 하며, v를 수정하면 안 돼요. 따라서 CharT& 타입의 매개변수는 허용되지 않고, 이동이 복사와 동일한 경우가 아니라면 CharT 타입도 허용되지 않아요. (C++11부터) |
반환값
제거된 요소의 개수를 반환해요.
복잡도
선형이에요.
참고
| 기능 테스트 매크로 | 값 | 표준 | 기능 |
|---|---|---|---|
__cpp_lib_algorithm_default_value_type |
202403 | (C++26) | 알고리즘의 목록 초기화 (1) |
예제
#include <iomanip>
#include <iostream>
#include <string>
int main()
{
std::string word{"startling"};
std::cout << "Initially, word = " << std::quoted(word) << '\n';
std::erase(word, 'l');
std::cout << "After erase 'l': " << std::quoted(word) << '\n';
auto erased = std::erase_if(word, [](char x)
{
return x == 'a' or x == 'r' or x == 't';
});
std::cout << "After erase all 'a', 'r', and 't': " << std::quoted(word) << '\n';
std::cout << "Erased symbols count: " << erased << '\n';
#if __cpp_lib_algorithm_default_value_type
std::erase(word, {'g'});
std::cout << "After erase {'g'}: " << std::quoted(word) << '\n';
#endif
}
가능한 출력이에요.
Initially, word = "startling"
After erase 'l', word = "starting"
After erase all 'a', 'r', and 't': "sing"
Erased symbols count: 4
After erase {'g'}: "sin"
같이 보기
erase |
문자를 제거하는 멤버 함수예요. [edit] |
|---|---|
remove, remove_if |
특정 기준을 만족하는 요소를 제거하는 함수 템플릿 및 알고리즘 함수 객체예요. [edit] |
ranges::remove, ranges::remove_if (C++20) (C++20) |
범위 기반으로 요소를 제거해요. [edit] |