根据字符串大小对字符串向量进行排序

sorting a string vector based on the string size

本文关键字:字符串 向量 排序      更新时间:2023-10-16

我想知道如何对字符串向量进行排序,以便字符数最少的字符串位于向量之上。例如,如果向量中有 ABCD、ABCDE、ABC。ABC登上了顶峰。我很想知道如何使用sort_if实现这一点以及谓词会是什么样子?也欢迎任何其他方法

创建自己的自定义函子来比较字符串的大小,并使用它来对字符串进行排序。

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);

在现代 c++ 中,我们可以使用 lambda 来做同样的事情

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

应该能够使用常规std::sort(first, last, compare) ,以及像这样的比较函数:

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

std::sort采用可选参数进行自定义比较

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );

您可以只定义一个基于长度进行比较的函数。