c++stl和std
C ++ STL std :: replace_if()函数 (C++ STL std::replace_if() function)
replace_if() function is a library function of algorithm header, it is used to replace the value in a given range based on the given unary function that should accept an element in the range as an argument and returns the value which should be convertible to bool (like 0 or 1), it returns value indicates whether the given elements can be replaced or not?
replace_if()函数是算法标头的库函数,用于根据给定的一元函数替换给定范围内的值,该函数应接受范围内的元素作为参数并返回应可转换为bool的值(如0或1),它返回值指示给定的元素是否可以替换?
Note: To use replace_if() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.
注意:要使用replace_if()函数 –包括<algorithm>头文件,或者您可以简单地使用<bits / stdc ++。h>头文件。
Syntax of std::replace_if() function
std :: replace_if()函数的语法
std::replace_if(
iterator start,
iterator end,
unary_function,
const T& new_value);
Parameter(s):
参数:
iterator start, iterator end – these are the iterators pointing to the starting and ending positions in the container, where we have to run the replace operation.
迭代器开始,迭代器结束 –这些迭代器指向容器中我们必须运行替换操作的开始和结束位置。
unary_function – is a unary function that will perform the condition check on all elements in the given range and the elements which pass the condition will be replaced.
unary_function –是一元函数,它将对给定范围内的所有元素执行条件检查,并且将替换通过条件的元素。
new_value – a value to be assigned instead of an old_value.
new_value –要分配的值,而不是old_value。
Return value: void – it returns noting.
返回值: void –返回注释。
Example: (Replacing EVEN number)
示例:(替换偶数)
//function to check EVEN value
bool isEVEN(int x)
{
if (x % 2 == 0)
return 1;
else
return 0;
}
Input:
vector<int> v{ 10, 20, 33, 23, 11, 40, 50 };
//replacing all EVEN elements with -1
replace_if(v.begin(), v.end(), isEVEN, -1);
Output:
-1 -1 33 23 11 -1 -1
C ++ STL程序演示std :: replace_if()函数的使用 (C++ STL program to demonstrate use of std::replace_if() function)
In this program, we have a vector and replacing all EVEN numbers with -1.
在此程序中,我们有一个向量,并将所有偶数替换为-1。
//C++ STL program to demonstrate use of
//std::replace_if() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//function to check EVEN value
bool isEVEN(int x)
{
if (x % 2 == 0)
return 1;
else
return 0;
}
int main()
{
//vector
vector<int> v{ 10, 20, 33, 23, 11, 40, 50 };
//printing vector elements
cout << "before replacing, v: ";
for (int x : v)
cout << x << " ";
cout << endl;
//replacing all EVEN elements with -1
replace_if(v.begin(), v.end(), isEVEN, -1);
//printing vector elements
cout << "after replacing, v: ";
for (int x : v)
cout << x << " ";
cout << endl;
return 0;
}
Output
输出量
before replacing, v: 10 20 33 23 11 40 50
after replacing, v: -1 -1 33 23 11 -1 -1
Reference: C++ std::replace_if()
翻译自: https://www.includehelp.com/stl/std-replace_if-function-with-example.aspx
c++stl和std