c++ - C++ 中类似 Python 的字符串乘法

标签 c++ c++11 stdstring

作为一名长期的 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/

相关文章:

c++ - `static constexpr` 在常量表达式中调用的函数是...错误?

c++ - 将非英文字符串存储在 std::string 中

c++ - 错误 : invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

c++ - 具有完整 C++11 支持的 Windows C++ 编译器(应该与 Qt 一起使用)

c++ - 如何在 C++ 中为模板函数实例创建快捷方式?

c++ - 递增引用变量不起作用

c++ - 素数程序无缘无故停在 20,031 的素数 225,149。没有错误信息

c++ - 使用非成员 ostream 重载函数打印任何 c++11 数组

c++ - VC++2010 似乎只在固定数组中分配一个 std::string

c++ - If 语句代替 while 循环