sorting the whole vector is waste of time: if all you need are the three largest elements, use nth_element
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <functional>
int func(std::vector<int> v)
{
if(v.size() < 3) throw std::runtime_error("Your vector is too small");
nth_element(v.begin(), v.begin()+3, v.end(), std::greater<int>());
return v[0] + v[1] + v[2];
}
int main()
{
std::cout << func({1,2,3,4,5,6,7,8,9,10,20,30}) << '\n';
}
|
demo: http://ideone.com/UxWpdt
Granted, copying before sort/nth_element is a waste of time too, the best way is really to maintain just the three integers and update them as you iterate through the vector.
There's even a library for that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/tail.hpp>
int func(const std::vector<int>& v)
{
using namespace boost::accumulators;
accumulator_set<int, features<tag::tail<right>>> acc(tag::tail<right>::cache_size = 3);
acc = for_each(v.begin(), v.end(), acc);
return accumulate(tail(acc).begin(), tail(acc).end(), 0);
}
int main()
{
std::cout << func({1,2,3,4,5,6,7,8,9,10,20,30}) << '\n';
}
|
demo: http://ideone.com/ySxuxX
|