You don't need a stringstream or an istringstream or a vector for this. std::sort
can be performed on a string directly. An std::string_view can be used to avoid copying (more on this later)
There seems to be 3 options how to make this work best. If you don't care about chewing up your original string you can perform the operations on it directly without ever copying anything. Here you will pass by reference:
std::string& AlphabetSoup(std::string& str) {
std::sort(str.begin(), str.end());
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str; // or omit this and change the return value to void
}
You can also pass by value which will copy your string and leave the original intact:
std::string AlphabetSoup(std::string str) {
std::sort(str.begin(), str.end());
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str;
}
Or you can pass in as a std::string_view
which will not copy.
std::string AlphabetSoup(std::string_view str) {
std::string s(str);
std::sort(s.begin(), s.end());
s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
return s;
}
The method I used to remove the spaces is known as the erase-remove idiom. The character specified in the remove()
function is moved to the end of the range (provided as parameters) where they can be efficiently erased. There are faster iterators on sorted sets that can speed things up as @TobySpeight pointed out but I haven't used them. (Namely std::lower_bound
and std::upper_bound
)
Consider providing test cases and output. This too will help reviewers and make it more likely for you to get solid answers.