G. Sliepen already took care of the big picture issues, where you get the most bang for the buck.
Still, there are a few issues with the code aside from using a sub-optimal algorithm:
You should consider
std::string_viewfor the string-argument, and for getting a temporary slice of a long-lived string.
Dynamic allocation is pretty expensive, and best avoided, both on calling a function if the input might not be in the desired format, and in the function itself.
See "What isstring_view?" and "How exactly isstd::string_viewfaster thanconst std::string&?" for more details.Now that the functions no longer allocate memory, or contain any other potential exception-thrower, mark them
noexceptso everyone knows (and the compiler enforces) that it won't throw. It won't do much of anything here, but is good documentation, informs the compiler if it only knows the declaration, and can be important later with using templated code consuming it for best performance and highest exception-safety guarantees.Also, mark them
constexprwhile you are at it, to allow use in constant expression, and encourage evaluation at compile-time and allow forcing that. AlsoThat is also a best-practice thing not actually changngchanging much of anything for your example program itself.You use
std::couttwice (whyever you don't chain itpush all togetherthe output into it in a single expression escapes me there, but that can be argued either way), andstd::endlonce. TheWriting (and keeping in mind) those two using-declaration doesn't look like a good investment, evendeclarations costs more than prefixing the uses withstd::. Even if you really dislike writingstd::, you don't write it less often.Don't force flushing a stream unless you really mean it, as it flushes performance down the drain. And in that case
std::endloutputs a newline and then flushes,stream << std::endlbeing exactly equivalent tostream << '\n' << std::flush. Thus if you really have to, better be explicit and usestd::flush.
Flushing is normally expensive buzy-workSee "What is the C++ iostreamendlfiasco?" for more detail.