举个简单的例子,假设我有一个函数int f(vector<int> v)
,由于某种原因,我需要在f
中多次对v
执行一些操作。与其在别处添加一个帮助函数(可能会增加混乱并影响可读性),这样做有什么优缺点(效率、可读性、可维护性等):
int f(vector<int> v)
{
auto make_unique = [](vector<int> &v)
{
sort(begin(v), end(v));
auto unique_end = unique(begin(v), end(v));
v.erase(unique_end, end(v));
};
auto print_vector = [](vector<int> const &v)
{
copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
cout << endl;
};
make_unique (v);
print_vector(v);
// And then the function uses these helpers a few more times to justify making
// functions...
}
还有其他更好的选择吗?
make_unique
。 - aaronman