algorithm_replace_copy
algorithm_replace_copy (치환하며 복사)
std::replace_copy는 소스 범위를 목적지 범위로 복사하면서, 기준을 만족하는 요소를 new_value로 치환해요. 원본을 변경하지 않아요.
출처: cppreference
본문
std::replace_copy는 소스 범위 [first, last)의 요소들을 목적지 범위 [d_first, std::next(d_first, std::distance(first, last)))로 복사하면서, 특정 기준을 만족하는 모든 요소를 new_value로 치환해요. <algorithm> 헤더에 정의되어 있어요.
template< class InputIt, class OutputIt, class T >
OutputIt replace_copy( InputIt first, InputIt last, OutputIt d_first,
const T& old_value, const T& new_value );
template< class InputIt, class OutputIt, class UnaryPred, class T >
OutputIt replace_copy_if
( InputIt first, InputIt last, OutputIt d_first,
UnaryPred p, const T& new_value );
replace_copy—operator==로old_value와 같은 요소를new_value로 치환해요.replace_copy_if— 술어p를 만족하는 요소를new_value로 치환해요.
반환값 (Return value)
복사된 마지막 요소 다음의 반복자예요.
복잡도 (Complexity)
N을 std::distance(first, last)라고 하면 정확히 N번의 p 적용(또는 비교)이 필요해요.
예제 (Example)
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> src{1, 2, 3, 4, 3, 6};
std::vector<int> dst;
std::replace_copy(src.begin(), src.end(), std::back_inserter(dst), 3, 30);
for (int x : dst) std::cout << x << ' ';
std::cout << '\n';
}
출력:
1 2 30 4 30 6