int main()
{
int age, count=0; //, i; // keep variables as local as possible!
std::vector<int> length;
std::cin >> age;
// you don't check for stream state nor validity of `age`:
if(!std::cin || age < 0) // possibly some upper limit, too??
// side note: if you use unsigned int, you only have
// to check this upper limit!
{
// some appropriate error handling
}
// optimisation: we know necessary capacity in advance, so let's prevent
// otherwise necessary re-allocations:
length.reserve(age);
//for(i=0;i<=age;i++)
for(int i = 0; i < age; i++) // variables as local as possible, remember?
// <= reads one candle too much; consider age == 2:
// you'll get candles for i == 0, i == 1 and i == 2!
{
// well no, you don't want to push back the counter itself (0, 1, 2, ...)
// you need to read in candle hights instead!
//length.push_back(i);
int height;
std::cin >> height;
// check input as before!
length.push_back(height);
}
std::sort(length.begin(), length.end());
int max = length.back();
// for(i=0;i<=length.size(); i++)
// ^ again, one element too much!
// ...
Well, at this point, you can be cleverer; you sorted already, so profit from! Usage of iterators makes it easier, you can directly iterate from back!
for(auto i = length.rbegin(); i != length.rend(); ++i)
{
if(*i != max)
{
count = i - length.rbegin();
break;
}
}
// special case: all candles have same height, then you would't have met the inner if:
if(count == 0)
{
count = length.size();
}
Actually, you can do without sorting first in just one single go:
int max = 0; // now let's assume we checked for negative values right from the start
// otherwise we'd need to use std::numeric_limits<int>::min() instead
// again I'd prefer the unsigned type...
for(auto height : length)
{
if(height == max)
++count;
else if(height > max)
count = 1;
// else: can ignore...
}
Hm... did you notice? We just processed in the same order than we read in the values. So we could do all in one single go:
for(int i = 0; i < age; ++i)
{
unsigned int height;
std::cin >> height;
// check validities!
// instead of pushing back, directly calculate what we are interested in:
if(height == max)
++count;
else if(height > max)
count = 1;
}