1

Not sure if I’ve posted the right question for what I’m actually asking but here it is. I am trying to print the maximum and minimum rainfall from the sumofrain vector along with the corresponding year from the yearly vector.

Just to make it clear if the maximum rainfall in the sumofrain vector was the 7th value in the vector then the year I would like being output is the 7th value in the yearly vector ect.

louiej15
  • 61
  • 7

3 Answers3

1

Given that the vectors yearly and sumofrain are not jagged, you can simply check the distance from the beginning.

// Get iterator to the max element in container.
auto it = std::max_element(std::begin(sumofrain), std::end(sumofrain));

// Get index of element pointed to by iterator.
auto index = std::distance(std::begin(sumofrain), it);

auto maxRain = *it;
auto maxYear = yearly[index];

std::cout << "Wettest year: " << maxYear << ". ";
std::cout << "Rainfall recorded: " << maxRain << " mm." << std:: endl;
Felix Glas
  • 15,065
  • 7
  • 53
  • 82
  • when using cout to display this what variable would i use? and thank you for your help. @snps – louiej15 Mar 04 '15 at 16:06
  • @louiej15 Both `maxRain` and `maxYear` have type `double` (value type of the containers), and you can output these using `std::cout` and `<<` operator. – Felix Glas Mar 04 '15 at 16:08
  • This brings the error, 'it,index,maxYear,maxRain' does not name a type – louiej15 Mar 04 '15 at 16:15
  • What compiler are you using? Possibly it's not c++11 compliant, required for (that usage of) the auto keyword. –  Mar 04 '15 at 16:15
  • @louiej15 The modern use of the `auto` keyword for type deduction is introduced in C++11, the second most recent standard (current is C++14). If you are using an old compiler that does not support the more recent standards you might get these errors. – Felix Glas Mar 04 '15 at 16:18
0

Store the sum-of-rain in a map of year -> double.

std::map<int, double>  rainfall;
while(file >> year >> month >> maxdeg >> mindeg >> afdays >> rainmm >> sunhours) 
  {
    rainfall[year] += rainmm;
    frost.push_back(afdays);
  }

Then, when the file is done reading, find the entry in the map with the lowest/highest rainfall, via e.g. Finding minimum value in a Map

The iterator you get back has ->first which is the year and ->second which is the actual amount of rainfall for that year.

Community
  • 1
  • 1
emvee
  • 4,371
  • 23
  • 23
0

You should store the iterator returned by max_element(sumofrain.begin(),sumofrain.end()) into a variable.

auto itMax = max_element(sumofrain.begin(),sumofrain.end());

Then, to find out the zero-based index of the found element:

itMax - sumofrain.begin();

And to find the value :

*itMax
Laurent LA RIZZA
  • 2,905
  • 1
  • 23
  • 41