将多个值插入向量 [英] Insert multiple values into vector

查看:74
本文介绍了将多个值插入向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: vector< T> 变量.我也有两个类型T的变量,第一个代表我要插入的向量中的值,第二个代表要插入的值.

I have a std::vector<T> variable. I also have two variables of type T, the first of which represents the value in the vector after which I am to insert, while the second represents the value to insert.

所以可以说我有这个容器: 1,2,1,1,2,2

So lets say I have this container: 1,2,1,1,2,2

根据上面的定义,两个值分别为2和3.然后,我想编写一个函数,将容器更新为包含以下内容:

And the two values are 2 and 3 with respect to their definitions above. Then I wish to write a function which will update the container to instead contain:

1,2,3,1,1,2,3,2,3

我正在使用c ++ 98和boost.我可以使用哪些std或boost函数来实现此功能?

I am using c++98 and boost. What std or boost functions might I use to implement this function?

迭代向量并使用std :: insert是一种方法,但是当人们意识到您需要记住要跳过刚刚插入的值时,它会变得混乱.

Iterating over the vector and using std::insert is one way, but it gets messy when one realizes that you need to remember to hop over the value you just inserted.

推荐答案

我可能会这样做:

vector<T> copy;
for (vector<T>::iterator i=original.begin(); i!=original.end(); ++i)
{
    copy.push_back(*i);
    if (*i == first)
        copy.push_back(second);
}
original.swap(copy);

如果需要,可以拨打电话保留在那里.您知道至少需要 original.size()元素的空间.您还可以对向量进行初始迭代(或使用 std :: count )以确定要保留的元素的确切数量,但是如果不进行测试,我不知道这是否会提高性能.

Put a call to reserve in there if you want. You know you need room for at least original.size() elements. You could also do an initial iteraton over the vector (or use std::count) to determine the exact amount of elements to reserve, but without testing, I don't know whether that would improve performance.

这篇关于将多个值插入向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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