Here is a reference implementation of std::max_element
.
template<class ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last)
{
if (first == last) {
return last;
}
ForwardIt largest = first;
++first;
for (; first != last; ++first) {
if (*largest < *first) {
largest = first;
}
}
return largest;
}
You can create your own algorithm by modifying this in the following way:
template<class ForwardIt>
ForwardIt max_element_nth(ForwardIt first, ForwardIt last, int n)
{
if (first == last) {
return last;
}
ForwardIt largest = first;
first += n;
for (; first < last; first += n) {
if (*largest < *first) {
largest = first;
}
}
return largest;
}
Of course it has the limitation of working only with random access iterators, but it certainly works for vector
.
double xmax = *max_element_nth(myvector.begin(),myvector.end(), 3);
double ymax = *max_element_nth(myvector.begin()+1,myvector.end(), 3);
double zmax = *max_element_nth(myvector.begin()+2,myvector.end(), 3);
But I'd rather do it by storing the (x, y, z) values in a structure, and take a vector of that. Then, you can use the standard max_element
with a custom comparator.