小编Chr*_*ph2的帖子

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

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

我的问题:这可以做得更惯用/更有效吗(或者我的代码甚至有缺陷)?

c++ stdstring c++11

6
推荐指数
1
解决办法
1514
查看次数

标签 统计

c++ ×1

c++11 ×1

stdstring ×1