Given two strings, find the common characters.Is there better implementation for this problem?#include<iostream>#include<string>#include<algorithm>std::string   find_intersection(std::string & first, std::string & second){   std::sort(std::begin(first),std::end(first));   std::sort(std::begin(second), std::end(second));   int length = std::min(first.length(), second.length());   std::string result(length,' ');   std::set_intersection(std::begin(first),std::end(first),std::begin(second),std::end(second),std::begin(result));   result.shrink_to_fit();   return result; }int main(){   std::string first=GermanTown;   std::string second=Georgia;    std::cout<<find_intersection(first,second)<<\n;   return 0;}
Find common characters
c++;algorithm;strings;c++11;c++14
For the same reasons as @DJanssens, I would like to compliment you for a simple and clean algorithm making proper use of the standard library. That may seem basic, but there are too many people ignoring the standard <algorithm> in the world, so I'm glad that you decided to use it. I only want to add two more things:First, I don't think that shrink_to_fit will do what you expect it to do. When you construct result, you allocate memory and fill it with spaces, so result's size probably grew to. shrink_to_fit will get rid of the allocated but unused memory, but it won't get rid of the extra spaces that you allocated at construction.What you can do is default-construct your std::string and use an std::back_inserter to fill it the lazy way. The std::back_inserter will perform some magic so that the result's push_back method is called whenever an element has to be added:std::string find_intersection(std::string & first, std::string & second){    std::sort(std::begin(first),std::end(first));    std::sort(std::begin(second), std::end(second));    std::string result;    std::set_intersection(        std::begin(first), std::end(first),        std::begin(second), std::end(second),        std::back_inserter(result)    );    return result; }