Up until Google+ imploded I was one of the moderators of their C++ Programming community. We emphasized modern features, standards conformance, and outreach to students. Frequently, though, we’d find ourselves stymied by two-bit educators who were actively hostile towards our efforts.
I remember one case vividly. A college student who had never before seen C++ came to the community looking for help with a simple assignment. They were to write a program that would create an array of one hundred integers, would populate these integers with the numbers from one to one hundred, would sum these integers, and output the result. As far as first steps in C++ go, it’s a pretty okay assignment: it’s well-defined and it gives you the chance to begin to explore how the language fits together.
“Start at the beginning,” I counseled the student. “Break it down into conceptual steps. What’s the very first thing that must be done? And the second? And so on?” And so, back and forth, we reached the following sequence:
- Define a constant representing both how many integers we needed and what the contents of the final integer should be
- Create an array of that many integers
- Fill that array with the numbers from one up to our constant
- Add that array
- Output the result
- Signal to our operating system that we’ve completed successfully
Simple enough, really. And once we had that sequence, it was time to ask the all-important modern C++ question: “what facilities does C++ offer to help make these tasks easier?” And that led to discussions of std::array, std::iota, std::accumulate, and more.
After much back and forth with an eager, enthusiastic student who really wanted to learn C++ the right way, we came up with the following code:
I’d like to emphasize: that’s modern C++. It uses only bog-standard C++ features. There’s nothing in there that should be in any way surprising to any competent C++ programmer.
The student was graded savagely for it. What the professor wanted, and the only thing he would accept, was: