-4
#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>
3
  • 3
    ranges::fold_left_first returns std::optional. Commented Mar 12, 2024 at 11:19
  • You can access the optional either with it's member functions has_value() / value() or using pointer syntax: if(v) { n = *v;} Commented Mar 12, 2024 at 11:35
  • You can use auto result. Then you can print the type of result using typeid(result).name(), based on that, you can handle it (call has_value()). Commented Mar 12, 2024 at 11:49

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.