简体   繁体   中英

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

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

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

std::vector<int> myVector;

//(...)


int a = myVector[1];

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.

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM