【问题标题】:Please explain the use of for_each function in this c++ code [duplicate]请解释此c ++代码中for_each函数的使用[重复]
【发布时间】:2021-11-27 15:32:37
【问题描述】:

我正在浏览techiedelight 文章link

我没明白std::for_each(s.begin(), s.end(), [&m](char &c) { m[c]++; }); [&m](char &c) { m[c]++; }的意思

#include <iostream>
#include <unordered_map>
#include <algorithm>
 
int main()
{
    std::unordered_map<char, int> m;
 
    std::string s("abcba");
    std::for_each(s.begin(), s.end(), [&m](char &c) { m[c]++; });
 
    char ch = 's';
 
    if (m.find(ch) != m.end()) {
        std::cout << "Key found";
    }
    else {
        std::cout << "Key not found";
    }
 
    return 0;
}

请有人解释它是如何工作的。 提前致谢。

【问题讨论】:

标签: c++ string algorithm dictionary stl


【解决方案1】:
[&m](char &c) { m[c]++; }

这是一个 lambda。 lambda 是使用简写的匿名类型函数对象。

它是粗略的简写:

struct anonymous_unique_secret_type_name {
  std::unordered_map<char, int>& m;
  void operator()(char& c)const {
    m[c]++;
  }
};
std::for_each(s.begin(), s.end(), anonymous_unique_secret_type_name{m} );

[&amp;m](char &amp;c) { m[c]++; } 既创建类型又构造实例。它捕获(通过引用)变量m,它在其主体中公开为m

作为类函数对象(又名函数对象),它有一个operator(),可以像函数一样调用。这里operator() 接受char&amp; 并返回void

所以for_each 在范围传递的每个元素(在本例中为字符串)上调用此函数对象。

【讨论】:

  • ...对地图做了什么?似乎您希望那篇文章能够充分解释这条线。
  • @sweenish 我认为是 lambda 语法混淆了 OP。我的意思是,我也可以解释一下int main 的含义。
  • 这可能是一个很好的假设,但他们询问了代码行。为了完整起见,我建议完成对该行的解释。不用客气。
猜你喜欢
  • 1970-01-01
  • 2011-03-22
  • 2016-09-06
  • 2016-09-28
  • 1970-01-01
  • 2013-08-13
  • 2023-03-31
  • 1970-01-01
  • 2013-04-06
相关资源
最近更新 更多