When we consider a vector that has only one kind of element, such as int or double, etc, it is very easy to understand the syntax of std::max_element to find the maximum value of the elements of a vector.

But what if the elements of the vector are structs and we want to find only the maximum of one type of element in the structs in the vector?

So far wrote this code only for vectors that contain simple elements, and this code is working, but how do we write the same code for a more general vector whose elements are structs (to find the maximum of just one type of element inside the vector structs?

And this is the output of the above program, which works for any range of elements in the simpler vector vector<int> vecInt:Code:#include <vector> #include <algorithm> using namespace std; struct S { string myWord; int a; int b; }; using namespace std; int main() { vector<int> vecInt; vector<S> vec; for(int j=0; j<10; j++) { //Initialize: vecInt.push_back(j); S tempS; tempS.a = j; tempS.b = 5+j; tempS.myWord = "aWord"; vec.push_back(tempS); } std::vector<int>::iterator result; std::vector<int>::iterator tempIter; size_t range = 3 ; // So far I have only applied std::max_element to the case of a // simple vector of ints: for(vector<int>::iterator itr=vecInt.begin( ) + 6 ; itr != vecInt.end( ) ; itr++) { size_t index = itr - vecInt.begin(); vector<int>::iterator first = itr -range; //std::max_element(first, last) returns an answer between [first,last) as half-open interval //and so we need to further increase last=itr+1 as follows // (or else the last element does not get compared): vector<int>::iterator last = itr + 1 ; result = std::max_element( first , last ); cout << "max element of vecInt between slot " << index -range << " and slot " << index << " is: " << *result << endl; cout << "vecInt[" << index << "] = " << *itr << endl; } }

max element of vecInt between slot 3 and slot 6 is: 6

vecInt[6] = 6

max element of vecInt between slot 4 and slot 7 is: 7

vecInt[7] = 7

max element of vecInt between slot 5 and slot 8 is: 8

vecInt[8] = 8

max element of vecInt between slot 6 and slot 9 is: 9

vecInt[9] = 9

But how does C++ restrict the std::max_element function to just one kind of element inside the structs contained in the vector, how do we write the code?

For instance how can we focus on the elements "a" in the struct S above, to find the maximum of vec[i].a over a range of indices i?