c++stl和std_std :: replace()函数以及C ++ STL中的示例

c++stl和std

C ++ STL std :: replace()函数 (C++ STL std::replace() function)

replace() function is a library function of algorithm header, it is used to replace an old value with a new value in the given range of a container, it accepts iterators pointing to the starting and ending positions, an old value to be replaced and a new value to be assigned.

replace()函数算法标头的库函数,用于在容器的给定范围内用新值替换旧值,它接受指向开始和结束位置的迭代器,要替换的旧值以及要分配的新值。

Note: To use replace() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

注意:要使用replace()函数 –包括<algorithm>头文件,或者您可以简单地使用<bits / stdc ++。h>头文件。

Syntax of std::replace() function

std :: replace()函数的语法

    std::replace(
        iterator start, 
        iterator end, 
        const T& old_value, 
        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.

    迭代器开始,迭代器结束 –这些迭代器指向容器中我们必须运行替换操作的开始和结束位置。

  • old_value – is the value to be searched and replaced with the new value.

    old_value –是要搜索并替换为新值的值。

  • new_value – a value to be assigned instead of an old_value.

    new_value –要分配的值,而不是old_value。

Return value: void – it returns noting.

返回值: void –返回注释。

Example:

例:

    Input:
    vector<int> v{ 10, 20, 10, 20, 10, 30, 40, 50, 60, 70 };
    
    //replacing 10 with 99
    replace(v.begin(), v.end(), 10, 99);
    
    Output:
    99 20 99 20 99 30 40 50 60 70

C ++ STL程序演示了std :: replace()函数的使用 (C++ STL program to demonstrate use of std::replace() function)

In this program, we have a vector and we are assigning a new value to an old value.

在此程序中,我们有一个向量,并且正在将新值分配给旧值。

//C++ STL program to demonstrate use of
//std::replace() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //vector
    vector<int> v{ 10, 20, 10, 20, 10, 30, 40, 50, 60, 70 };

    //printing vector elements
    cout << "before replacing, v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    //replacing 10 with 99
    replace(v.begin(), v.end(), 10, 99);

    //printing vector elements
    cout << "after replacing, v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

输出量

before replacing, v: 10 20 10 20 10 30 40 50 60 70
after replacing, v: 99 20 99 20 99 30 40 50 60 70

Reference: C++ std::replace()

参考: C ++ std :: replace()

翻译自: https://www.includehelp.com/stl/std-replace-function-with-example.aspx

c++stl和std

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值