1. 程式人生 > 其它 >c++ std標準庫 演算法<algorithm> 替換 replace() 條件替換replace_if()

c++ std標準庫 演算法<algorithm> 替換 replace() 條件替換replace_if()

技術標籤:# 4.1 C++c++stlreplace_ifreplace

std::replace

簡介:
replace() 演算法會用新的值來替換和給定值相匹配的元素。

函式原型

template <class ForwardIterator, class T>
void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value);

官方手冊
http://www.cplusplus.com/reference/algorithm/replace/


std::replace_if

簡介:
將滿足條件的值替換為新值。

函式原型

template <class ForwardIterator, class UnaryPredicate, class T>
void replace_if (ForwardIterator first, ForwardIterator last,
                   UnaryPredicate pred, const T& new_value );

官方手冊
http://www.cplusplus.com/reference/algorithm/replace_if/


使用示例:

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>

using namespace std;

void main()
{
	vector<int> v1;
	int dim[] = { 1,2,3,4,5,6,7,8,9 };

	cout << "【原始v1】" << endl;
	v1.assign(dim, dim + 9);
	copy
(v1.begin(), v1.end(), ostream_iterator<int>(cout, ", ")); cout << endl; cout << "【將第7個數替換為99】" << endl; replace(v1.begin(), v1.end(), 7, 99); copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, ", ")); cout << endl; cout << "【將小於6的數替換為11】" << endl; replace_if(v1.begin(), v1.end(), bind2nd(less<int>(), 6), 11); copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, ", ")); cout << endl; }

image-20201217162612402