如何在C ++中替换向量中的特定值? [英] How to replace specific values in a vector in C++?
问题描述
我有一个带有某些值(3、3、6、4、9、6、1、4、6、6、7、3)的向量,我想用54替换每个3或用54替换每个6例如1,依此类推.
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.
因此,我需要先遍历向量,获取[i]值,搜索并用54替换每个3,但仍要保留相关的 positions.std :: set
vector :: swap 是一个好方法吗?我什至不知道该如何开始:(我不能使用 push_back
,因为那样就不能保持正确的值顺序,这很重要.
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? I am 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; I am just a beginner :)
推荐答案
作业的工具是 std :: replace
:
The tool for the job is std::replace
:
std::vector<int> vec { 3, 3, 6, /* ... */ };
std::replace(vec.begin(), vec.end(), 3, 54); // replaces in-place
查看实际效果 .
See it in action.
这篇关于如何在C ++中替换向量中的特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!