Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ vector last element field

I have a vector vec of structures. Such a structure has elements int a, int b, int c. I would like to assign to some int var the element c, from the last structure in a vector. Please can you provide me with this simple solution? I'm going circle in line like this:

var = vec.end().c; 
like image 741
berndh Avatar asked Jan 11 '13 09:01

berndh


People also ask

How do you find the last element of a vector?

If you want to access the last element of your vector use vec. back() , which returns a reference (and not iterator). Do note however that if the vector is empty, this will lead to an undefined behavior; most likely a crash.

What is VEC end ()?

The C++ function std::vector::end() returns an iterator which points to past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector.

How do you remove the last element of a vector?

The C++ function std::vector::pop_back() removes last element from vector and reduces size of vector by one.


2 Answers

The immediate answer to your question as to fetching access to the last element in a vector can be accomplished using the back() member. Such as:

int var = vec.back().c; 

Note: If there is a possibility your vector is empty, such a call to back() causes undefined behavior. In such cases you can check your vector's empty-state prior to using back() by using the empty() member:

if (!vec.empty())    var = vec.back().c; 

Likely one of these two methods will be applicable for your needs.

like image 188
WhozCraig Avatar answered Oct 13 '22 10:10

WhozCraig


vec.end() is an iterator which refers the after-the-end location in the vector. As such, you cannot deference it and access the member values. vec.end() iterator is always valid, even in an empty vector (in which case vec.end() == vec.begin())

If you want to access the last element of your vector use vec.back(), which returns a reference (and not iterator). Do note however that if the vector is empty, this will lead to an undefined behavior; most likely a crash.

like image 34
CygnusX1 Avatar answered Oct 13 '22 08:10

CygnusX1