Search code examples
c++vectorstructure

How can I get a field from the last element of a vector in C++?


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;

Solution

  • 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.