Python’s range() in 20 lines of C++

The Python language does not have an iteration-based for-loop in the style of C and C++; instead it uses a Python list (or tuple) in conjunction with the keywords for and in. Python 2 uses the helper function range() to create a suitable list, while Python 3 implements this function as an iterator class (to avoid a potential delay before the first iteration of the loop due to populating a very large list). If we were to implement this in C++, we could populate a std::vector and iterate over that, but this could potentially suffer from the space-and-time overheads of the Python 2 version. So instead we’ll choose to use iterators in the style of the STL containers (actually, if you know your Standard Library iterator categories, it’s forward iterators we want to emulate, however I haven’t used the actual iterator types available because of only wanting to be compatible with range-for, not the standard containers).

Continue reading “Python’s range() in 20 lines of C++”

printf() to a std::string

Just in case you weren’t already aware, a part of the upcoming C++20 Standard is a text formatting library (based upon the popular, free, third-party {fmt} library). It looks like being a great addition to the Standard Library, providing ease-of-use, performance and type-safety.

Before we put the <iomanip> and <cstdio> C++ headers into the museum however, lets look at something which is also possible in Modern C++, using a printf()-style format string to construct a std::string. The prototype of this function is therefore:

std::string string_printf(const char *fmt,...);
Continue reading “printf() to a std::string”