有人能推荐一种简洁明了的方法来实现这个吗:
float CalculateGoodness(const Thing& thing);
void SortThings(std::vector<Thing>& things)
{
// sort 'things' on value returned from CalculateGoodness, without calling CalculateGoodness more than 'things.size()' times
}
显然,我可以使用一个调用
CalculateGoodness
的比较函数来使用std::sort
,但这样会在每个Thing
与其他元素进行比较时多次调用它,如果CalculateGoodness
很耗费时间,那就不好了。我可以创建另一个std::vector
来存储评分,并对其进行std::sort
,然后以相同的方式重新排列things
,但我看不到一个整洁的方法来做到这一点。有什么想法吗?编辑:抱歉,我应该说不修改
Thing
,否则这是一个相当容易解决的问题 :)
Thing
要比调用CalculateGoodness
更便宜,当然,算法复杂性也优于比较函数方法。 - undefinedswap
。我的编译器具有移动语义,这可能使得甚至不需要使用它。而且它还支持lambda表达式,所以我可以让代码变得更加漂亮 :) 我真希望我能给这个点赞两次! - undefined