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;
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.
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.
The C++ function std::vector::pop_back() removes last element from vector and reduces size of vector by one.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With