溫馨提示×

c++ replace函數(shù)的用法是什么

c++
小億
164
2023-11-29 14:15:08
欄目: 編程語言

在C++中,std::replace()函數(shù)用于在容器中替換指定范圍內(nèi)的元素。

它的函數(shù)聲明如下:

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

參數(shù)解釋:

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

函數(shù)功能: std::replace()會依次遍歷[first, last)范圍內(nèi)的元素,并將與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