Sort string's characters into alphabetic order Any improvements that I can make with this code?
Also, is there another way to convert a vector to a string variable without using a for ranged-based loop? From the posts I've seen for converting, I only saw printing the vector instead of returning a string.

#include &lt;string&gt;
#include &lt;vector&gt;
#include &lt;sstream&gt;
#include &lt;algorithm&gt;
#include &lt;iterator&gt;

using namespace std;

std::string AlphabetSoup(string str) {
std::vector&lt;char&gt;letters;

 istringstream iss(str);

 copy(istream_iterator&lt;char&gt;(iss),
        istream_iterator&lt;char&gt;(),
        back_inserter(letters));

 std::sort(letters.begin(),letters.end());

 //Regrouping the characters into a string
 std::string orderedString;
 for(auto element : letters)
 {
     orderedString += element;
 }

 return orderedString;
}
Don't use using namespace std

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&amp; AlphabetSoup(std::string&amp; 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.