Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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

like image 240
karthik Avatar asked Mar 29 '11 05:03

karthik


People also ask

How do you access a specific element in a vector?

Element access: reference operator [g] – Returns a reference to the element at position 'g' in the vector. at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.

How do you retrieve an element from a vector?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.

How do you find the elements in a vector array?

Use std::find_if() with std::distance() This is a recommended approach to finding an element in a vector if the search needs to satisfy a specific logic eg, finding an index of element in the vector that is a prime number using prime number logic.

How do you change the position of an element in a vector?

You can do that using at. You can try out the following simple example: const size_t N = 20; std::vector<int> vec(N); try { vec.at(N - 1) = 7; } catch (std::out_of_range ex) { std::cout << ex. what() << std::endl; } assert(vec.at(N - 1) == 7);


2 Answers

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

std::vector<int> myVector;

//(...)


int a = myVector[1];
like image 70
Jean-Marc Pelletier Avatar answered Sep 16 '22 14:09

Jean-Marc Pelletier


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.

like image 25
Raninf Avatar answered Sep 18 '22 14:09

Raninf