gpt4 book ai didi

c++ - 使用 lambda 函数定义非常小的辅助函数是一种好的风格吗?

转载 作者:可可西里 更新时间:2023-11-01 18:27:23 24 4
gpt4 key购买 nike

作为一个愚蠢的例子,假设我有一个函数 int f(vector<int> v) ,出于某种原因,我需要对 v 进行一些操作在f中多次.与其将辅助函数放在其他地方(这可能会增加困惑并损害可读性),不如这样做的优点和缺点是什么(效率、可读性、可维护性等):

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...
}

或者是否有一些首选的替代方案?

最佳答案

这种局部作用域函数的优点是它们不会用“辅助”定义污染周围的代码——所有行为都可以限制在一个单一的作用域内。由于它们可以访问周围函数的词法范围,因此无需传递许多参数即可将它们用于分解行为。

您还可以使用它们来创建小型 DSL,以抽象出功能的机械细节,以便您以后可以更改它们。您为重复值定义常量;为什么不对代码做同样的事情?

举个小例子,状态机:

vector<int> results;
int current;
enum { NORMAL, SPECIAL } state = NORMAL;

auto input = [&]{ return stream >> current; }
auto output = [&](int i) { results.push_back(i); };
auto normal = [&]{ state = NORMAL; };
auto special = [&]{ state = SPECIAL; };

while (input()) {
switch (state) {
case NORMAL:
if (is_special(current)) special(); else output(current);
break;
case SPECIAL:
if (is_normal(current)) normal();
break;
}
}

return results;

缺点是您可能会不必要地隐藏和特化可能对其他定义有用的通用函数。 uniquifyprint_vector 函数值得浮出并重用。

关于c++ - 使用 lambda 函数定义非常小的辅助函数是一种好的风格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com