假设我有一个初始化并使用lambda的二进制搜索功能:
bool const custom_binary_search(std::vector<int> const& search_me)
{
auto comp = [](int const a, int const b)
{
return a < b;
}
);
return std::binary_search(search_me.begin(),search_me.end(),comp);
}
Run Code Online (Sandbox Code Playgroud)
没有指出这是完全多余的,只关注lambda; 每次声明和定义lambda对象是否昂贵?它应该是静态的吗?lambda是静态的意味着什么?
类型为<some anonymous lambda class>的变量'comp'可以是静态的,几乎与任何其他局部变量一样,即它是相同的变量,每次运行此函数时指向相同的内存地址).
但是,请注意使用闭包,这会导致细微的错误(按值传递)或运行时错误(按引用传递),因为闭包对象也只初始化一次:
bool const custom_binary_search(std::vector<int> const& search_me, int search_value, int max)
{
static auto comp_only_initialized_the_first_time = [max](int const a, int const b)
{
return a < b && b < max;
};
auto max2 = max;
static auto comp_error_after_first_time = [&max2](int const a, int const b)
{
return a < b && b < max2;
};
bool incorrectAfterFirstCall = std::binary_search(std::begin(search_me), std::end(search_me), search_value, comp_only_initialized_the_first_time);
bool errorAfterFirstCall = std::binary_search(std::begin(search_me), std::end(search_me), search_value, comp_error_after_first_time);
return false; // does it really matter at this point ?
}
Run Code Online (Sandbox Code Playgroud)
请注意,'max'参数只是为了引入您可能想要在比较器中捕获的变量,而"custom_binary_search"实现的功能可能不是很有用.
| 归档时间: |
|
| 查看次数: |
6962 次 |
| 最近记录: |