#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>
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<int>());
// 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;
}