The answer you link is about searching a vector for an element that meets a given criterion. Finding the maximum is different, because you have to consider all elements before you know the maximum element.
std::max_element
lets you choose a comparison, so you can compare only for id
easily:
auto max = *std::max_element(vec.begin(),
vec.end(),
[](const st& a,const st& b) { return a.id < b.id; });
You mentioned *max_element
, hence I suppose that you are aware that it returns an iterator that you can dereference. However, be aware that if the container is empty the above will break (undefined behavior due to dereferencing the end
iterator) and the safer way is:
auto it = std::max_element(vec.begin(),
vec.end(),
[](const st& a,const st& b) { return a.id < b.id; });
if (it == vec.end()) throw "max_element called on emtpy vector";
auto max = *it;
PS
[...] without the use of for loop?
Do not confuse using algorithms with "no loops". The link above has a possible implementation and if you study it you will notice that it isnt magic, but just a plain loop. The advantage of the alogrithm is expressiveness and less possibilities for mistakes.