CLion17: lambda

上一节function pointer的function作为lambda e.g.

void foreach(const std::vector<int>& nums, void(*func)(int)){
    for (int num: nums) func(num);
}

int main() {
    std::vector<int> nums = {1, 5, 4, 2, 3};
    auto lambda = [](int v){std::cout << "Value: "<< v << std::endl;};
    foreach(nums, lambda);
    std::cin.get();
}

lambda: essentially a function specified to be invoked later.

[]: 如果要从外部传参:pass-by-value[=](ALL)或者pass-by-reference[&](ALL), 或者每个参数逐个声明 >> 具体参考cppreference网站中的lambda这部分:

capture

事实上,最前面的代码中[]内部无论传递=还是&都不对,因为foreach中传递的function pointer:raw parameterized:

err

Solid:

void foreach(const std::vector<int>& nums, const std::function<void(int)>& func){
    for (int num: nums) func(num);
}

int main() {
    std::vector<int> nums = {1, 5, 4, 2, 3};
    int a = 100;
    auto lambda = [&a](int v){std::cout << "Value: "<< v << a << std::endl;};
    foreach(nums, lambda);
    std::cin.get();
}
Value: 1100
Value: 5100
Value: 4100
Value: 2100
Value: 3100

Irrelevant: Achtung⚠️:std::find_if

Find element in range
Returns an iterator to the first element in the range [first,last) for which pred returns true. If no such element is found, the function returns last.

The behavior of this function template is equivalent to:

template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}

e.g.

// find_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::find_if
#include <vector>       // std::vector

bool IsOdd (int i) {
  return ((i%2)==1);
}

int main () {
  std::vector<int> myvector;

  myvector.push_back(10);
  myvector.push_back(25);
  myvector.push_back(40);
  myvector.push_back(55);

  std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
  std::cout << "The first odd value is " << *it << '\n';

  return 0;
}

推荐阅读更多精彩内容