algorithm_remove

algorithm_remove (요소 제거)

std::remove는 대상 범위에서 값이 일치하거나 술어를 만족하는 요소를 "제거"해요. 실제로는 제거된 요소들이 범위의 끝으로 옮겨지고, 새 범위의 끝 반복자를 돌려줘요.

출처: cppreference

본문

std::remove는 대상 범위 [first, last)에서 특정 기준을 만족하는 모든 요소를 "제거"해요. <algorithm> 헤더에 정의되어 있어요.

template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );

template< class ForwardIt, class UnaryPred >
ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPred p );
  • removeoperator==value와 같은 모든 요소를 제거해요.
  • remove_if — 술어 p가 참을 반환하는 모든 요소를 제거해요.

제거는 실제 삭제가 아니라, 남는 요소들이 범위의 앞쪽으로 옮겨지는 방식이에요. 병렬 실행 정책을 받는 오버로드도 있어요.

반환값 (Return value)

새 범위의 끝(past-the-end)을 가리키는 반복자예요. 위 반복자부터 원래 last까지의 요소들은 지정되지 않은 유효한 상태지만 불확정값이에요.

복잡도 (Complexity)

Nstd::distance(first, last)라고 하면 정확히 N번의 p 적용(또는 비교)이 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 3, 7};
    auto it = std::remove(v.begin(), v.end(), 3);
    v.erase(it, v.end());
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
}

출력:

1 2 4 5 7

더 알아보기 (Learn more)

cppreference