gpt4 book ai didi

c++ - 这个 C++/C++11 结构是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:52 25 4
gpt4 key购买 nike

我有这段代码。我不明白这个结构是什么意思。我知道这段代码从输入中读取数字并在 unordered_map 中计算它的频率。但是什么是[&](int x) 是什么意思? input(cin) 代表什么?我的意思是括号中的“cin”? for_each 如何从 input(cin) 迭代到空 eof 参数?我不明白这整个结构。

unordered_map<int,int> frequency;
istream_iterator<int> input(cin);
istream_iterator<int> eof;

for_each(input, eof, [&] (int x)
{ frequency[x]++; });

最佳答案

istream_iterator允许您迭代地从 istream 中提取项目,您将其传递给构造函数。 eof 对象解释如下:

A special value for this iterator exists: the end-of-stream; When an iterator is set to this value has either reached the end of the stream (operator void* applied to the stream returns false) or has been constructed using its default constructor (without associating it with any basic_istream object).

for_each是一个循环构造,它采用迭代器 #1 并递增它,直到它与迭代器 #2 相等。这里它采用包装标准输入的迭代器 cin并增加它(这转化为提取项目)直到没有更多的输入可以使用——这使得 input 比较等于 eof 并且循环结束。

构造 [&] (int x) { frequency[x]++; } 是一个 anonymous function ;它只是一种内联编写函数的简写方式。用

可以达到大致相同的效果
unordered_map<int,int> frequency; // this NEEDS to be global now
istream_iterator<int> input(cin);
istream_iterator<int> eof;

void consume(int x) {
frequency[x]++;
}

for_each(input, eof, consume);

简而言之:这段代码从标准输入中读取整数,直到消耗完所有可用数据,并记录每个整数在 map 中出现的频率。

关于c++ - 这个 C++/C++11 结构是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597823/

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