0

I have written code that outputs the total rainfall for a set amount of years. My question is how would I just display the year with the largest and smallest rainfall i.e the maximum and minimum of the dataset with the corresponding year.

The output i have so far is: (but i just want the maximum and minimum of the vector with the corresponding year so with this output, only 2011 and 2012 should be displayed)

noodle
  • 19
  • 1
  • 2
  • 9
  • 1
    What do you think you should do? – Mats Petersson Mar 03 '15 at 21:49
  • Possible duplicate of http://stackoverflow.com/questions/9874802/how-can-i-get-the-max-or-min-value-in-a-vector-c – SameOldNick Mar 03 '15 at 21:50
  • I've already looked at that but it doesn't help me display the year also @ub3rst4r – noodle Mar 03 '15 at 21:51
  • @MatsPetersson I'm not sure on how to display the year aswell, thats why i've posted the question on here – noodle Mar 03 '15 at 21:51
  • @noodle: please edit your code with the correct indent, it will help people to understand your code easier...For your question, you can create a vector to hold all the value of your rainfall for each year. Then, do a for loop to find your min and max value. – Hoang Minh Mar 03 '15 at 21:56
  • @HoangMinh I'm extremely new to c++ and I’m not really sure what the correct indentation sorry, – noodle Mar 03 '15 at 21:58

1 Answers1

1

std::max_element http://www.cplusplus.com/reference/algorithm/max_element/ std::min_element http://www.cplusplus.com/reference/algorithm/min_element/

Benilda Key
  • 2,836
  • 1
  • 22
  • 34
  • would this also display the corresponding year as that is what is causing the difficulty? – noodle Mar 03 '15 at 22:28
  • After using std::max_element and std::min_element use std::distance (http://www.cplusplus.com/reference/iterator/distance/) to get the index of the max and min elements. The year corresponding to the max element is as follows: yearly[iMaxElement]. The year corresponding to the min element is yearly[iMinElement]. – Benilda Key Mar 03 '15 at 22:38
  • The max and min now work perfectly thank you but could you go into more detail about how to display the year aswell? – noodle Mar 03 '15 at 23:18
  • I already answered that question in my previous comment about std::distance. Here is some untested code. I do not have time to test it for you. auto itMaxElement = std::max_element(rainfall.begin(), rainfall.end()); auto iMaxElement = std::distance(rainfall.begin(), itMaxElement); // iMaxElement is now the index of the max element. auto yearThatCorrespondsToMaxElement = yearly[iMaxElement]; – Benilda Key Mar 03 '15 at 23:24