C++ print a sequence

 

This is a post for C++ beginners. Not an easy role in the world of programming languages. But, I know it can be a rewarding one.

So, this is the situation. You are into intensive C++ std lib sampling and learning. You have a lot of little snippets. One thing has annoyed you a lot, but you have given up on it. You will do it later.

How to print a C++ sequence (or range) from one single and nice generic function.  Easy. But with no trailing comma. Not easy. Not hard either. That function finalized by you would be proof you are advancing.

In case you want such a function, to start with it, for the output like on the image above, here is the code.

The discussion comes later. Do not ignore it.

This ‘thing’ above can print anything to which begin and end can be found. For example

Explanation

I said “begin and end can be found”. This is different from “has begin() and end() methods”. Here is the (sort of a official) diagram representing a sequence

A sequence concept
A sequence concept. Iterators including.

There are (generic) std::begin() and std::end() functions. They return those two begin and end iterators as on the diagram above. That same diagram and concept of a sequence it represents, do apply to native arrays and all the types that can be logically visualized as a sequence.

We operate using this knowledge. Key to C++ is your ability to think abstract.  Not to get pulled down into the low-level details of (for example) implementations of std lib containers. That comes later. And is not mandatory.

That is why sequence_print looks simple. It is a high level code and algorithm , hiding a lot of complexity.

  1. think
  2. think abstract

I was deliberately vague. Don’t hesitate to ask in the comments bellow. I am especially interested how you might improve this code.

Hint: here is my hint, but ultimately I would like to see your version using std::format.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.