As a longtime Python programmer, I really appreciate Python's string multiplication feature, like this:
> print("=" * 5) # =====
Because there is no *
overload for C++ std::string
s, I devised the following code:
#include <iostream>
#include <string>
std::string operator*(std::string& s, std::string::size_type n)
{
std::string result;
result.resize(s.size() * n);
for (std::string::size_type idx = 0; idx != n; ++idx) {
result += s;
}
return result;
}
int main()
{
std::string x {"X"};
std::cout << x * 5; // XXXXX
}
My question: Could this be done more idiomatic/effective (Or is my code even flawed)?
you cannot multiply a string.
No, you can't do this in 'C' as far as I think.In python multiplication of a string by a number is defined as 'repetition' of the string that number of times. One way you can do this in 'C++'(a superset of 'C' language) is through 'operator overloading'.
Multiplication. You can do some funny things with multiplication and strings. When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer).
No, you can't. However you can use this function to repeat a character.
What about simply using the right constructor for your simple example:
std::cout << std::string(5, '=') << std::endl; // Edit!
For really multiplying strings you should use a simple inline function (and reserve()
to avoid multiple re-allocations)
std::string operator*(const std::string& s, size_t n) {
std::string result;
result.reserve(s.size()*n);
for(size_t i = 0; i < n; ++i) {
result += s;
}
return result;
}
and use it
std::cout << (std::string("=+") * 5) << std::endl;
See a Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With