Quixotic
Quixotic

Reputation: 2464

How does *max_element() work in this snippet?

int N = 6;
vector< vector<int> > A(N, vector<int>(3));

/* Do operation with A */

cout<<(*max_element(a.begin(),a.end()))[2]<<endl;

I am not sure what does max_element is doing here. Can anybody help in understanding this?

PS: I came across this while reviewing indy256 's solution in the TopCoder practice room, while solving this problem.

Upvotes: 0

Views: 89

Answers (1)

jrok
jrok

Reputation: 55425

Lexicographicaly comparing (because the elements are vectors), max_element finds the largest element in the vector a. It returns an iterator that's immediately dereferenced, giving a reference to the element. It then calls calls operator[], giving back the element at index 2 that's ultimately streamed to cout.

A less terse equivalent would be:

auto it = max_element(a.begin(), a.end());
int i = (*it)[2]; // better make sure the vector has at least 3 elements!

cout << i;

Upvotes: 5

Related Questions