作为一名长期的 Python 程序员,我非常欣赏 Python 的字符串乘法功能,如下所示:
> print("=" * 5) # =====
Run Code Online (Sandbox Code Playgroud)
因为*
C++没有重载std::string
,所以我设计了以下代码:
#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
}
Run Code Online (Sandbox Code Playgroud)
我的问题:这可以做得更惯用/更有效吗(或者我的代码甚至有缺陷)?