5.替换
- replace()
函数模板为:
template<class ForwardIt, class T>
void replace(ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value)
{
for (; first != last; ++first) {
if (*first == old_value) {
*first = new_value;
}
}
}
//replace_if
template<class ForwardIt, class UnaryPredicate, class T>
void replace_if(ForwardIt first, ForwardIt last,
UnaryPredicate p, const T& new_value)
{
for (; first != last; ++first) {
if(p(*first)) {
*first = new_value;
}
}
}
说明:
1. 第一种形式:replace替换容器的[first,last]范围内部中和old_value等值的元素,替换为new_value.
2. 第二种形式:replace_if替换的容器范围中满足一元规则p的元素为new_value.
例子:
---------省略---------------
array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
replace(s.begin(), s.end(), 8, 88);
---------省略---------------
replace_if(s.begin(), s.end(), std::bind(std::less<int>(), std::placeholders::_1, 5), 55);//小于5的替换为55
---------省略---------------
结果为;
5 7 4 2 88 6 1 9 0 3
5 7 55 55 99 6 55 9 55 55