错误:无法在初始化时将 'std::Optional<int>' 转换为 'const int'

问题描述 投票:0回答:1
#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>
c++ fold std-ranges c++23 stdoptional
1个回答
0
投票

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;
}

© www.soinside.com 2019 - 2024. All rights reserved.