C++ STL 向量:从索引获取迭代器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/671423/
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
C++ STL Vectors: Get iterator from index?
提问by mpen
So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like vector.insert(pos, first, last)
is the function I want... except I only have first and last as ints. Is there any nice way I can get an iterator to these values?
所以,我写了一堆代码,通过 index[] 访问 stl 向量中的元素,但现在我只需要复制向量的一个块。看起来vector.insert(pos, first, last)
是我想要的功能......除了我只有第一个和最后一个作为整数。有什么好的方法可以获得这些值的迭代器吗?
回答by dirkgently
Try this:
尝试这个:
vector<Type>::iterator nth = v.begin() + index;
回答by bayda
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
@dirkgently 提到的方式( v.begin() + index )
对向量来说又好又快
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
但最通用的方式和随机访问迭代器的工作时间也是恒定的。 std::advance
( v.begin(), index )
EDIT
differences in usage:
编辑
使用差异:
std::vector<>::iterator it = ( v.begin() + index );
or
或者
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
在@litb 注释之后添加。
回答by Viktor Sehr
Also; auto it = std::next(v.begin(), index);
还; auto it = std::next(v.begin(), index);
Update: Needs a C++11x compliant compiler
更新:需要一个 C++11x 兼容编译器
回答by TimW
回答by yves Baumes
Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:
实际上,std::vector 旨在在需要时用作 C 选项卡。(据我所知,C++ 标准要求向量实现 -替换维基百科中的数组)例如,根据我的说法,执行以下操作是完全合法的:
int main()
{
void foo(const char *);
sdt::vector<char> vec;
vec.push_back('h');
vec.push_back('e');
vec.push_back('l');
vec.push_back('l');
vec.push_back('o');
vec.push_back('/0');
foo(&vec[0]);
}
Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...
当然,要么 foo 不能复制作为参数传递的地址并将其存储在某个地方,要么您应该确保在您的程序中永远不要在 vec 中推送任何新项目,或请求更改其容量。或者风险分段错误...
Therefore in your exemple it leads to
因此,在您的示例中,它导致
vector.insert(pos, &vec[first_index], &vec[last_index]);