#include <iostream>
#include <numeric>
#include <ranges>
#include <vector>
#include <string>
#include <string_view>
int main() {
auto str = (
std::views::iota(1)
| std::ranges::views::take(5)
| std::ranges::views::transform([](int x) -> std::string_view {
return std::to_string(x) + "|";
})
| std::ranges::views::join
);
for (const char ch : str) {
std::cout << ch;
}
return 0;
}
I'm new to functional programming in cpp. I want to generate first five natural numbers and translate them to string, then join them and print it.
If I use std::string
for return type of lambda for transform, it throws many error on compile time. I thought that I should change it into std::string_view
. I changed so, and it compiled without compile error. However, if I use std::string_view
there, the lambda function returns only reference for string, and translated string that on stack memory is removed on memory when lambda ends. So, the program doesn't print anything.
How can I fix it?