I want to get all digits in a std::string but without using a loop (myself; what the code I'm calling uses, I don't mind). An alternative view of the request is: remove all non-digits from the string, leaving only the digits. I know that I can find all digit in a string using code like this:
std::string get_digits(std::string input) {
std::string::size_type next_digit(0u);
for (std::string::size_type pos(0u);
input.npos != (pos = input.find_first_of("0123456789"));
++pos) {
input[next_digit++] = input[pos];
}
input.resize(next_digit);
return input;
}
However, this function uses a loop. std::string doesn't provide a function find_all() or something! Ideally, the string is maniulated in-place (the code above moves it but it is easily changed to take a reference).
When there are multiple alternatives, I'll promise to post profiling results of how good the different approaches work on some lengthy text.
std::partitionto move all the digits to the front of the string. If order matters, then there isstd::stable_partition.std::remove_if(followed byerase). Should be faster thanstd::partition, since it only cares about first part, and doesn't mind leaving random garbage in the second part. Preserves order (of elements not removed) for free.std::move(): you are right, the arguments are considered local variables and are automatically moved from (I don't think it harms, though, as I think arguments are not eligible for copy elision).