replace specific values in a vector but keep order?

hello!

i have a vector with some values
(3, 3, 6, 4, 9, 6, 1, 4, 6, 6, 7, 3)
and i want to replace each 3 with a 54 or each 6 with a 1, for example and so on.

so i need to go through the vector first, get the [i] value, search and replace each 3 with a 54 but still keep relevant positions.std::set
is vector::swap a good way? not even sure how to begin this :(
i can't use push_back as that would not keep the correct order of values as that is important.

please keep it simple, just a beginner :)
I don't understand what order you want? What is relevant positions. You mentioned std::set so do you mean you want sorted order?
the order of everything must stay the same, so i only want to swap out a 3 for a 54 (or whatever).
so the new vector would start as 54, 54, 29 (if a 6 is supposed to be a 29)....
In that case all you have to do is, like you said, go through the vector and replace all the occurrences of 3 with 54. Should be easy using a loop. If you want you can use std::replace from <algorithm>
std::replace(vec.begin(), vec.end(), 3, 54);
In general replacing a value of an element does not change the order of elements in a vector or an array.
Last edited on
Topic archived. No new replies allowed.