在前面插入向量

Inserting into a vector at the front(在前面插入向量)
本文介绍了在前面插入向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..
iterator insert ( iterator position, const T& x );

std::Vector类的插入操作符的函数声明.

Is the function declaration of the insert operator of the 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() 

与在代码 1 中使用返回的迭代器相比,成本高"在计算上进行评估,或者两者都应该同样便宜/成本高?

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

推荐答案

获取插入点的效率一点也不重要 - 每次执行时不断地将现有数据洗牌的低效率会让它相形见绌插入.

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)