c++foldstd-rangesc++23stdoptional

error: cannot convert 'std::optional<int>' to 'const int' in initialization


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

Compiled using 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>

Solution

  • Function ranges::fold_left_first returns std::optional<int> rather then int:

    https://en.cppreference.com/w/cpp/algorithm/ranges/fold_left_first

    Here's the corrected code:

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