我想知道如何对字符串向量进行排序,使得字符数量最少的字符串位于向量之上.例如,如果向量具有ABCD,ABCDE,ABC.ABC达到顶峰.我有兴趣知道如何用sort_if实现这一点以及谓词会是什么样子?任何其他方法也欢迎
and*_*dre 16
创建自己的自定义函子来比较字符串的大小,并使用它来对字符串进行排序.
struct compare {
bool operator()(const std::string& first, const std::string& second) {
return first.size() < second.size();
}
};
std::vector<std::string> v;
compare c;
std::sort(v.begin(), v.end(), c);
Run Code Online (Sandbox Code Playgroud)
应该可以使用常规std::sort(first, last, compare),和这样的比较功能:
bool compareLen(const std::string& a, const std::string& b)
{
return (a.size() < b.size());
}
Run Code Online (Sandbox Code Playgroud)