当我使用 Stream Library ( http://jscheiny.github.io/Streams/api.html# ) 时,我可以在 Java-Streams 中执行类似的操作:
#include "Streams/source/Stream.h"
#include <iostream>
using namespace std;
using namespace stream;
using namespace stream::op;
int main() {
list<string> einkaufsliste = {
"Bier", "Käse", "Wurst", "Salami", "Senf", "Sauerkraut"
};
int c = MakeStream::from(einkaufsliste)
| filter([] (string s) { return !s.substr(0,1).compare("S"); })
| peek([] (string s) { cout << s << endl; })
| count()
;
cout << c << endl;
}
它给出了这个输出:
Salami
Senf
Sauerkraut
3
在 C++20 中,我发现了范围,它们看起来有望实现相同的目标。但是,当我想构建类似的函数式编程风格时,它不起作用:
#include <iostream>
#include <ranges>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<string> einkaufsliste = {
"Bier", "Käse", "Wurst", "Salami", "Senf", "Sauerkraut"
};
int c = einkaufsliste
| ranges::views::filter([] (string s) { return !s.substr(0,1).compare("S"); })
| ranges::for_each([] (string s) { cout << s << " "; })
| ranges::count();
;
}
尽管像这样的文章( https://www.modernescpp.com/index.php/c-20-the-ranges-library)提出了这样的功能,但接缝范围的事情并不意味着像这样工作。
test.cpp:16:67: note: candidate expects 3 arguments, 1 provided
16 | | ranges::for_each([] (string s) { cout << s << " "; })
| ^
test.cpp:17:29: error: no match for call to '(const std::ranges::__count_fn) ()'
17 | | ranges::count();
| ^
有什么想法我仍然可以在 C++20 中做类似的事情吗?