sorting a string vector based on the string size

Should be able to use regular std::sort(first, last, compare), and a compare function like this:

bool compareLen(const std::string& a, const std::string& b)
{
    return (a.size() < b.size()); 
}

Make your own custom functor to compare the size of string(s) and use that to sort the strings.

struct compare {
    inline bool operator()(const std::string& first,
            const std::string& second) const
    {
        return first.size() < second.size();
    }
};

std::vector<std::string> v;
compare c;
std::sort(v.begin(), v.end(), c);

In modern c++ we can use a lambda to do the same

std::vector<std::string> v;
std::sort(v.begin(), v.end(), []
    (const std::string& first, const std::string& second){
        return first.size() < second.size();
    });

Tags:

C++

Stl

Vector