Question 10
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
#include <array>
#include <iostream>
int total(const std::array<int, 4>& a) {
int t = 0;
for (int x : a) t += x;
return t;
}
int main() {
std::array<int, 3> q{1, 2, 3};
std::cout << total(q) << '\n';
return 0;
}
- A total must take a vector
- B The size is part of the type: std::array<int, 3> and std::array<int, 4> are different types, so q cannot bind to the parameter Correct
- C q must be non-const
- D Range-for does not work on std::array
Correct Answer: Option B
Make total a template on N, or accept std::span<const int>, which works for any size.
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!