Question 20
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#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!