#include <vector>
#include <ranges>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
const vector<int> v = {1, 2, 3};
const int n = ranges::fold_left_first(v | views::transform([](int i){return i*i;}), plus<int>())
return 0;
}
Скомпилировано с использованием g++14.
prog.cc: In function 'int main()':
prog.cc:10:42: error: cannot convert 'std::optional<int>' to 'const int' in initialization
10 | const int n = ranges::fold_left_first(v | views::transform([](int i){return i*i;}), plus<int>())
| ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| |
| std::optional<int>
Вы можете получить доступ к необязательному параметру либо с помощью его функций-членов has_value()/value(), либо с помощью синтаксиса указателя: if (v) { n = *v;}
Вы можете использовать auto result. Затем вы можете распечатать тип результата, используя typeid(result).name(), и на основании этого вы можете его обработать (вызов has_value()).





Функция ranges::fold_left_first возвращает std::optional<int>, а не int:
https://en.cppreference.com/w/cpp/algorithm/ranges/fold_left_first
Вот исправленный код:
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
#include <optional>
using namespace std;
int main() {
const vector<int> v = {1, 2, 3};
std::optional<int> result = ranges::fold_left_first(v | views::transform([](int i) { return i * i; }), plus<>());
// Check if the result has a value and use it
if (result.has_value()) {
const int n = result.value();
cout << "The sum of the squares is: " << n << endl;
} else {
cout << "The vector is empty." << endl;
}
return 0;
}
ranges::fold_left_firstвозвращаетсяstd::optional.