When I use the Stream Library (http://jscheiny.github.io/Streams/api.html#) I can do similar things like in 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;
}
It gives this output:
Salami
Senf
Sauerkraut
3
In C++20 I discovered ranges, which look promising to achieve the same thing. However, when I want to build something similar functional programming style it does not work:
#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();
;
}
Seams that the ranges thing is not meant to work like this, although articles like this (https://www.modernescpp.com/index.php/c-20-the-ranges-library) suggest such a feature.
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();
| ^
Any ideas how I still could do similar things in C++20?