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
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();
});
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With