patterncppMinor
Python-style string multiplication
Viewed 0 times
stylestringpythonmultiplication
Problem
When people migrate from Python to C++, they're often bothered by the fact that C++ strings don't support multiplication like Python's strings do.
This is an attempt at providing such a solution:
For example, using these, the typical "print a Christmas tree of asterisks" task could be written something like this:
[Of course, in this particular case, we're only multiplying single-character strings, so the
Note that the trailing
std::string does have a constructor that supports creating a string with one character repeated a specified number of times. But, if the pattern to be repeated is more than one character long, C++ provides no convenient solution.This is an attempt at providing such a solution:
#include
std::string operator*(std::string const &in, size_t m) {
std::string ret;
for (size_t i = 0; i < m; i++)
ret += in;
return ret;
}
std::string operator*(size_t m, std::string const &in) {
std::string ret;
for (size_t i = 0; i < m; i++)
ret += in;
return ret;
}For example, using these, the typical "print a Christmas tree of asterisks" task could be written something like this:
int main() {
using namespace std::literals;
std::cout > width;
for (int i = 1; i < width; i+=2)
std::cout << " "s * ((width - i-1)/2) << "*"s * i << "\n";
}[Of course, in this particular case, we're only multiplying single-character strings, so the
std::string ctor would work as well.]Note that the trailing
s to make the string literal an std::string rather than a char const * is necessary--at least one operand of a user-defined operator must be a class or enumeration (or reference to a class or enumeration).Solution
Code duplication:
There is a code duplication in the overloads of the operator. I believe that the second should call the first with parameters swapped, or vice versa.
Last feature:
The last thing I would add, aside from what @Justin mentioned, is some support for
Do note that in this case reserving might make sense.
There is a code duplication in the overloads of the operator. I believe that the second should call the first with parameters swapped, or vice versa.
Last feature:
The last thing I would add, aside from what @Justin mentioned, is some support for
std::basic_string<>. Although it will introduce abundance of template parameters, the code will be more or less generic.Do note that in this case reserving might make sense.
Context
StackExchange Code Review Q#146783, answer score: 7
Revisions (0)
No revisions yet.