LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Predict the Output · Question 17

accumulate and max_element on a vector Answer, explanation & discussion

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

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

main.cpp
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> v{3, 9, 4, 9, 1};
    auto it = std::max_element(v.begin(), v.end());
    double avg = std::accumulate(v.begin(), v.end(), 0.0) / v.size();
    std::cout << *it << ' ' << (it - v.begin()) << ' ' << avg << ' '
              << std::count(v.begin(), v.end(), 9) << '\n';
    return 0;
}
  • A 9 1 5.2 2 Correct
  • B 9 3 5.2 2
  • C 9 1 5 2
  • D 9 1 5.2 1
Correct Answer: Option A

max_element returns the first maximum (index 1). Starting accumulate at 0.0 makes the sum a double, so 26 / 5 = 5.2.

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