插入到前面的矢量 [英] Inserting into a vector at the front

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

问题描述

iterator insert ( iterator position, const T& x );

std :: Vector class。

此函数的返回类型是一个指向插入元素的迭代器。我的问题是,给定这种返回类型,什么是最有效的方式(这是一个更大的程序的一部分,我运行速度是至关重要的,所以我寻找计算高效的方式)。是以下吗?

This function's return type is an iterator pointing to the inserted element. My question is, given this return type, what is the most efficient way (this is part of a larger program I am running where speed is of the essence, so I am looking for the most computationally efficient way) of inserting at the beginning. Is it the following?

//Code 1
vector<int> intvector;
vector<int>::iterator it;
it = myvector.begin();
for(int i = 1; i <= 100000; i++){
    it = intvector.insert(it,i);
}

//Code 2
vector<int> intvector;
for(int i = 1; i <= 100000; i++){
    intvector.insert(intvector.begin(),i);
}

基本上,在代码2中,是参数

Essentially, in Code 2, is the parameter,

intvector.begin() 

Costly在计算方面进行评估,与在代码1中使用返回的迭代器相比,或者应该同样便宜/昂贵吗?

"Costly" to evaluate computationally as compared to using the returned iterator in Code 1 or should both be equally cheap/costly?

推荐答案

p>获得插入点的效率至少是没有问题的 - 每次插入时,不断地改变现有数据的效率就会很低。

The efficiency of obtaining the insertion point won't matter in the least - it will be dwarfed by the inefficiency of constantly shuffling the existing data up every time you do an insertion.

为此使用std :: deque,这是它的设计目的。

Use std::deque for this, that's what it was designed for.

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

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