How to replace specific values in a vector in C++?

前端 未结 4 1971
抹茶落季
抹茶落季 2021-01-06 18:50

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

4条回答
  •  情话喂你
    2021-01-06 19:07

    The tool for the job is std::replace:

    std::vector vec { 3, 3, 6, /* ... */ };
    std::replace(vec.begin(), vec.end(), 3, 54); // replaces in-place
    

    See it in action.

提交回复
热议问题