This post will discuss how to conditionally replace values in a vector in C++.

1. Using std::replace_if

The best option to conditionally replace values in a vector in C++ is using the std::replace_if function. It assigns a new value to all the elements in the specified range for which the provided predicate holds true. For example, the following code replaces all values greater than 5 with 10.

Download  Run Code

Output:

10 3 10 10 1 2 10

2. Using std::transform

Another good alternative is to use the std::transform, which applies an operation sequentially to each of the elements in the given range. This operation may be a unary operation, a lambda expression, or an object implementing the () operator.

Download  Run Code

Output:

-6 -3 -8 9 -1 2 -8

3. Using Loop

We can even write our custom routine to conditionally replace values in a vector. This is demonstrated below using a for-loop. The code negates the value of every element of the vector.

Download  Run Code

Output:

-6 -3 -8 9 -1 2 -8

4. Using std::replace

To replace all occurrences of an element in a vector with another, we can use the standard algorithm std::replace from the <algorithm> header. The following code example shows invocation for this function:

Download  Run Code

Output:

6 3 7 9 1 2 7

5. Using std::find_if

Finally, we can use the standard algorithm std::find to conditionally replace only the “first” occurrence of an element within the vector. For example, the following code finds and replaces the first negative value with 0.

Download  Run Code

Output:

6 3 8 0 1 -2 8

That’s all about conditionally replacing values in a vector in C++.