C++ 使用擦除和插入替换向量中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15998783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:59:05  来源:igfitidea点击:

Replacing elements in vector using erase and insert

c++vectorinsertiteratorerase

提问by Nikolai Stiksrud

void replace(vector<string> my_vector_2, string old, string replacement){

    vector<string>::iterator it;
    for (it = my_vector_2.begin(); it != my_vector_2.end(); ++it){

        if (*it==old){
            my_vector_2.erase(it);
            my_vector_2.insert(it,replacement);

        }
    }

}

So, I'd like this function to replace all occurrences of the string old in the vector with the string replacement. But when calling this function, it simply doesn't change the vector at all. I'm not sure if I am using the erase and insert functions properly. Any ideas?

所以,我希望这个函数用字符串替换来替换向量中所有出现的字符串 old 。但是当调用这个函数时,它根本不会改变向量。我不确定我是否正确使用了擦除和插入功能。有任何想法吗?

回答by alexrider

At first you need to pass vector by reference, not by value.

首先你需要通过引用传递向量,而不是通过值。

void replace(vector<string>& my_vector_2, string old, string replacement){

Second erase and insert invalidatesit, you need to update it with new iterator returned by erase

第二次擦除和插入使其无效,您需要使用擦除返回的新迭代器更新它

it = my_vector_2.erase(it);  
it = my_vector_2.insert(it,replacement);

回答by Kerrek SB

There's an ready-made algorithmfor your problem:

有一个现成的算法可以解决您的问题:

#include <algorithm>
#include <string>
#include <vector>

std::vector<std::string> v;  // populate

std::replace(v.begin(), v.end(), "old", "new");

回答by bash.d

You are passing your std::vectoras a value. In order to Change the std::vectoryou pass to the function, declare it as a reference

你正在传递你的std::vector作为一个值。为了更改std::vector您传递给函数的内容,请将其声明为引用

void replace(vector<string>& my_vector_2, string old, string replacement){ }

The &denotes that you pass your std::vectorby reference and so you can access the object you passed.

&表示你通过你的std::vector参考,并且这样你就可以访问你传递的对象。

And don't erase the element, simply replace it.

并且不要擦除元素,只需替换它。