Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting a string vector based on the string size [duplicate]

Tags:

c++

stl

vector

I wanted to know how I can sort a string vector such that the string with the least amount of characters is on top of the vector. For instance if the vector has ABCD,ABCDE,ABC in it. ABC gets to the top.I would be interested to know how this could be achieved with sort_if and what the predicate would look like ? Any other methods are also welcome

like image 466
MistyD Avatar asked Sep 16 '13 15:09

MistyD


2 Answers

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();
    });
like image 150
andre Avatar answered Nov 20 '22 11:11

andre


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()); 
}
like image 7
Mats Petersson Avatar answered Nov 20 '22 12:11

Mats Petersson