當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::replace_copy()用法及代碼示例

C++ STL std::replace_copy() 函數

replace_copy()函數是算法頭的庫函數,用於替換範圍內的值,將替換後的結果中的元素複製,接受序列的範圍[開始,結束],結果序列的開始位置,舊值和新值,它將範圍中的所有 old_value 替換為 new_value,並將範圍複製到從結果開始的範圍。

注意:使用 replace_copy() 函數 - 包括<algorithm>標題或者您可以簡單使用<bits/stdc++.h>頭文件。

std::replace_copy() 函數的語法

    std::replace_copy(
        iterator start, 
        iterator end, 
        iterator start_result, 
        const T& old_value, 
        const T& new_value);

參數:

  • iterator start, iterator end- 這些是指向容器中開始和結束位置的迭代器,我們必須在那裏運行替換操作。
  • iterator start_result- 是結果序列的開始迭代器。
  • old_value- 要替換​​的值。
  • new_value- 要分配的值而不是 old_value。

返回值: iterator- 它返回一個迭代器,指向寫入結果序列的最後一個元素之後的元素。

例:

    Input:
    //an array (source)
    int arr[] = { 10, 20, 30, 10, 20, 30, 40, 50, 60 };
    
    //declaring a vector (result sequence)
    vector<int> v(6);
    
    //copying 6 elements of array to vector
    //by replacing 10 to -1
    replace_copy(arr + 0, arr + 6, v.begin(), 10, -1);
    
    Output:
    vector (v):-1 20 30 -1 20 30

用於演示 std::replace_copy() 函數使用的 C++ STL 程序

在這個程序中,我們有一個數組,我們通過用 -1 替換 10 將它的 6 個元素複製到一個向量中。

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

int main()
{
    //an array
    int arr[] = { 10, 20, 30, 10, 20, 30, 40, 50, 60 };

    //declaring a vector
    vector<int> v(6);

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

    cout << "vector (v):";
    for (int x:v)
        cout << x << " ";
    cout << endl;

    //copying 6 elements of array to vector
    //by replacing 10 to -1
    replace_copy(arr + 0, arr + 6, v.begin(), 10, -1);

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

    cout << "vector (v):";
    for (int x:v)
        cout << x << " ";
    cout << endl;

    return 0;
}

輸出

before replacing, Array (arr):10 20 30 10 20 30 40 50 60
vector (v):0 0 0 0 0 0
after replacing, Array (arr):10 20 30 10 20 30 40 50 60
vector (v):-1 20 30 -1 20 30

參考:C++ std::replace_copy()



相關用法


注:本文由純淨天空篩選整理自 std::replace_copy() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。