How can I get a field from the last element of a vector in C++?
C++VectorStructureC++ Problem Overview
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;
C++ Solutions
Solution 1 - C++
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.
Solution 2 - C++
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.
Solution 3 - C++
Use back()
:
var = vec.back().c;
Solution 4 - C++
Try this: var = vec.back().c;
Also you may modify your code like:
var = vec.rbegin()->c;
In both versions first make sure that the vector is not empty!
Solution 5 - C++
var = vec.back().c;
is what you want.
end()
returns the iterator (not an element) past-the-end of the vector. back()
returns a reference to the last element. It has a counterpart front()
as well.
Solution 6 - C++
You can simply use back
as it returns a reference to the last element.
var = vec.back().c
Solution 7 - C++
You can use the std:vector<T>:back()
function, e.g. vec.back().c
.
See http://www.cplusplus.com/reference/vector/vector/back/
Solution 8 - C++
The following code works for me.
int var;
var = *(std::end(bar)-1);
std::cout<<var<<std::endl;