C++ 如何让迭代器到达向量的特定位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6935389/
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
how to get iterator to a particular position of a vector
提问by A. K.
Suppose i have a
假设我有一个
std::vector<int> v
//and ...
for(int i =0;i<100;++i)
v.push_back(i);
now i want an iterator to, let's say 10th element of the vector.
现在我想要一个迭代器,让我们说向量的第 10 个元素。
without doing the following approach
不做以下方法
std::vector<int>::iterator vi;
vi = v.begin();
for(int i = 0;i<10;i++)
++vi;
as this will spoil the advantage of having random access iterator for a vector.
因为这会破坏向量的随机访问迭代器的优势。
回答by Cory Nelson
This will work with any random-access iterator, such as one from vector
or deque
:
这将适用于任何随机访问迭代器,例如 fromvector
或deque
:
std::vector<int>::iterator iter = v.begin() + 10;
If you want a solution that will work for any type of iterator, use next
:
如果您想要一个适用于任何类型迭代器的解决方案,请使用next
:
std::vector<int>::iterator iter = std::next(v.begin(), 10);
Or if you're not on a C++11 implementation, advance
:
或者,如果您不使用 C++11 实现,则advance
:
std::vector<int>::iterator iter = v.begin();
std::advance(iter, 10);
回答by pyroscope
Just add 10 to the iterator. They are intended to "feel" like pointers.
只需将 10 添加到迭代器。它们旨在“感觉”像指针。