samedi 23 septembre 2017

Python-like string multiplication in C++

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::strings, 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)?

Aucun commentaire:

Enregistrer un commentaire