假设我有一个初始化并使用 lambda 的二进制搜索函数:
bool 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);
}
没有指出这是完全多余的,只关注 lambda;每次都声明和定义那个 lambda 对象是不是很昂贵?它应该是静态的吗? lambda 是静态的意味着什么?
最佳答案
类型为
但是,请注意使用闭包,这会导致细微的错误(按值传递)或运行时错误(按引用传递),因为闭包对象也只初始化一次:
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 ?
}
请注意,“max”参数只是为了引入一个您可能希望在比较器中捕获的变量,而这个“custom_binary_search”实现的功能可能不是很有用。
关于c++ - lambda 是静态的是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19376193/