std::replace_copy, std::replace_copy_if
cppreference.com
<tbody>
</tbody>
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 ); |
(1) | |
template< class InputIt, class OutputIt, class UnaryPredicate, class T > OutputIt replace_copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p, const T& new_value ); |
(2) | |
[first, last) , d_first, , , new_value. , old_value, , p true. .
[first, last)
|
||
| d_first | ||
| old_value | , | |
| p | , true , . :
| |
| new_value | , | |
-InputIt InputIterator.
| ||
-OutputIt OutputIterator.
| ||
, .
last - first .
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)
{
for (; first != last; ++first) {
*d_first++ = (*first == old_value) ? new_value : *first;
}
return d_first;
}
|
template<class InputIt, class OutputIt,
class UnaryPredicate, class T>
OutputIt replace_copy_if(InputIt first, InputIt last, OutputIt d_first,
UnaryPredicate p, const T& new_value)
{
for (; first != last; ++first) {
*d_first++ = p( *first ) ? new_value : *first;
}
return d_first;
}
|
, , 5, 99.
#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>
int main()
{
std::vector<int> v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
std::replace_copy_if(v.begin(), v.end(),
std::ostream_iterator<int>(std::cout, " "),
[](int n){return n > 5;}, 99);
std::cout << '\n';
}
:
5 99 4 2 99 99 1 99 0 3
.
| , ( ) |