温馨提示×

c++ replace函数的用法是什么

c++
小亿
92
2023-11-29 14:15:08
栏目: 编程语言

在C++中,std::replace()函数用于在容器中替换指定范围内的元素。

它的函数声明如下:

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

参数解释:

  • firstlast是迭代器,表示要替换的范围。
  • old_value是要被替换的值。
  • new_value是要替换的新值。

函数功能: std::replace()会依次遍历[first, last)范围内的元素,并将与old_value相等的元素替换为new_value

示例用法:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 4, 3, 2, 1};

    std::replace(numbers.begin(), numbers.end(), 3, 6);

    for (int num : numbers) {
        std::cout << num << " ";
    }
    // 输出: 1 2 6 4 5 4 6 2 1

    return 0;
}

在上述示例中,std::replace(numbers.begin(), numbers.end(), 3, 6)将容器numbers中所有的值为3的元素替换为6。最后,我们遍历并输出修改后的容器元素。

0