c++ replace関数の構文は?
C++のstd::replace()関数は、コンテナ内の指定された範囲の要素を置き換えるために使用されます。
その関数の宣言は次のとおりです。
template< class ForwardIt, class T >
void replace( ForwardIt first, ForwardIt last, const T& old_value, const T& new_value );
パラメータの説明:
- firstやlastは、置換対象の範囲を表すイテレータです。
- 古い値が置換される値をold_valueにする。
- new_value は置換する新しい値です。
関数の機能:
std::replace()は[first, last)範囲内の要素を順番に走査し、old_valueと同じ要素をnew_valueに置き換えます。
このフレーズをネイティブな日本語で言い換えてください。1つ目のオプションのみが必要です。使用例:
#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 に置き換えます。最後に、変更後のコンテナの要素を反復処理して出力します。