LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 19

Building a container from a view with ranges::to (C++23) Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <ranges>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words{"modern", "c++", "is", "expressive", "and", "fast"};
    auto longer = words | std::views::filter([](const std::string& w) { return w.size() > 3; })
                        | std::views::transform([](const std::string& w) { return w.size(); })
                        | std::ranges::to<std::vector>();
    for (auto n : longer) std::cout << n << ' ';
    std::cout << "| " << longer.size() << '\n';
    return 0;
}
  • A 6 10 4 | 3 Correct
  • B modern expressive fast | 3
  • C 6 3 2 10 3 4 | 6
  • D 6 10 | 2
Correct Answer: Option A

ranges::to materialises a lazy pipeline into a real container – here a vector of the lengths of words longer than three letters.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links