GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::replace_copy - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. algorithm
  3. replace_copy

最終更新日時: 2026年08月25日 12時11分17秒 (JST)
Akira Takahashi が更新

履歴 編集

function template
<algorithm>

std::replace_copy

namespace std {
  template <class InputIterator, class OutputIterator, class T>
  OutputIterator
    replace_copy(InputIterator first,
                 InputIterator last,
                 OutputIterator result,
                 const T& old_value,
                 const T& new_value);     // (1) C++98

  template <class InputIterator, class OutputIterator, class T>
  constexpr OutputIterator
    replace_copy(InputIterator first,
                 InputIterator last,
                 OutputIterator result,
                 const T& old_value,
                 const T& new_value);     // (1) C++20

  template <class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class T>
  ForwardIterator2
    replace_copy(ExecutionPolicy&& exec,
                 ForwardIterator1 first,
                 ForwardIterator1 last,
                 ForwardIterator2 result,
                 const T& old_value,
                 const T& new_value);     // (2) C++17
}

概要

イテレータ範囲[first, last)のうち、指定された値と一致する要素を指定された値に置き換え、その結果を出力の範囲へコピーする。

テンプレートパラメータ制約

  • *first と new_value は result へ書き込み可能であること

事前条件

  • [first,last) と [result,result + (last - first)) の範囲が重なっていてはならない

効果

[result,result + (last - first)) 内のイテレータ i について、*(first + (i - result)) == old_value である場合は new_value が代入され、そうでない場合は *(first + (i - result)) が 代入される。

戻り値

result + (last - first)

計算量

正確に last - first 回の比較を行う

例

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

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

  // 1 の要素を全部 10 に置き換えたものを出力する
  std::replace_copy(v.begin(), v.end(),
    std::ostream_iterator<int>(std::cout, ","), 1, 10);
}

出力

3,10,2,10,2,

実装例

template <class InputIterator, class OutputIterator, class T>
OutputIterator replace_copy(InputIterator first, InputIterator last, OutputIterator result,
                            const T& old_value, const T& new_value) {
  for ( ; first != last; ++first)
    *result++ = *first == old_value ? new_value : *first;
  return result;
}

関連項目

  • ranges::replace_copy

参照

  • P0202R3 Add Constexpr Modifiers to Functions in <algorithm> and <utility> Headers
  • P0467R2 Iterator Concerns for Parallel Algorithms
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.