C++ 如何使用c ++中的指定位置获取Vector中的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5468346/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:13:56  来源:igfitidea点击:

How to get the element in Vector using the specified position in c++?

c++stl

提问by karthik

How to get the element by providing position in vector template?

如何通过在矢量模板中提供位置来获取元素?

回答by Jean-Marc Pelletier

You access std::vector elements just like a regular C array:

您可以像访问常规 C 数组一样访问 std::vector 元素:

std::vector<int> myVector;

//(...)


int a = myVector[1];

回答by Raninf

You could use the 'at' function (someVector.at(somePosition) gets you the element at somePosition), or you could use someVector[somePosition]. It's like a more developed array.

您可以使用 'at' 函数(someVector.at(somePosition) 为您获取 somePosition 处的元素),或者您可以使用 someVector[somePosition]。它就像一个更发达的阵列。

The difference between using the at function is that it will throw an exception if you give it an invalid position, while the []s don't check for things like that.

使用 at 函数的区别在于,如果给它一个无效的位置,它将抛出异常,而 [] 不会检查类似的事情。

回答by amit

There are 2 ways to accomplish what you want (for a vector say Vec):

有两种方法可以完成您想要的操作(对于向量说 Vec):

  (1) Use at() function eg. Vec.at(index)

  (2) Use like a normal array eg. Vec[index]

回答by Alok Save

Indexing works on Vectors, So just Acces it by using index. Similar to arrays.

索引适用于向量,因此只需使用索引访问它。类似于数组。