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.
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 <string>
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: ";
int width;
std::cin >> 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).
copy
builtin function won't write past the end of the array, so no extra housekeeping is needed. \$\endgroup\$