使用擦除和插入替换向量中的元素 [英] Replacing elements in vector using erase and insert

查看:35
本文介绍了使用擦除和插入替换向量中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

        }
    }

}

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

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?

推荐答案

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

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

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

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

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

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

这篇关于使用擦除和插入替换向量中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆