LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Predict the Output · Question 20

std::span views of a vector Answer, explanation & discussion

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

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

main.cpp
#include <iostream>
#include <span>
#include <vector>

int sum(std::span<const int> s) {
    int t = 0;
    for (int x : s) t += x;
    return t;
}

int main() {
    std::vector<int> v{1, 2, 3, 4, 5, 6};
    std::span<int> all(v);
    all[0] = 10;
    std::cout << sum(all) << ' ' << sum(all.first(2)) << ' ' << sum(all.subspan(2, 3)) << ' ' << v[0] << '\n';
    return 0;
}
  • A 30 12 12 10 Correct
  • B 21 3 12 1
  • C 30 12 9 10
  • D 30 12 12 1
Correct Answer: Option A

A span refers to the vector's elements, so all[0] = 10 changes v. Sums: all = 30, first two = 12, elements 2..4 = 3 + 4 + 5 = 12.

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