作为一名长期的 Python 程序员,我非常欣赏 Python 的字符串乘法功能,如下所示:
> print("=" * 5) # =====
因为 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
}
我的问题:这是否可以做得更惯用/更有效(或者我的代码甚至有缺陷)?
最佳答案
简单地使用 right constructor 怎么样?对于您的简单示例:
std::cout << std::string(5, '=') << std::endl; // Edit!
对于真正的乘法 strings 你应该使用一个简单的内联函数(和 reserve()
来避免多重重新分配)
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;
}
并使用它
std::cout << (std::string("=+") * 5) << std::endl;
查看 Live Demo
关于c++ - C++ 中类似 Python 的字符串乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379006/