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

17

我想知道如何对字符串向量进行排序,使得具有最少字符的字符串位于向量的顶部。例如,如果向量中包含ABCD,ABCDE和ABC,则ABC应该排在最前面。我想知道如何使用sort_if实现,并且谓词应该是什么样子?也欢迎使用其他方法。


没有 std::sort_if()。但是有一个重载的std::sort()采用谓词。该谓词会比较参数的长度,如果它们相等,则比较字符串的词法顺序;否则,如果第一个参数更短,则返回 true - Dietmar Kühl
FYI - 这些答案现在已经非常过时了,现在不需要过载运算符,只需使用lambda表达式即可! - Babra Cunningham
使用lambda表达式进行排序的示例:std::sort(words.begin(), words.end(), [](std::string a, std::string b) {return a.length() < b.length(); }); - hmofrad
3个回答

26

创建自定义函数对象来比较字符串的大小,并将其用于对字符串进行排序。

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

3
如果这些字符串长度相等,你可能希望按字典序对它们进行排序。函数调用运算符应该是“const”。 - Dietmar Kühl
你不需要创建一个函数对象来实现这个。一个简单的比较函数也可以做到。 - Zac Howland
@DietmarKühl 我认为如果它们的长度相同,你只需要保持稳定。我猜这取决于提问者。 - BoBTFish
1
@ZacHowland:虽然从语义上讲这是正确的,但在实践中,函数对象可以被内联,而使用函数指针作为谓词时通常无法内联。 - Dietmar Kühl
那已经不再是真的了(实际上已经有一段时间了):https://dev59.com/12445IYBdhLWcg3wcJ2O - Zac Howland

7

您应该能够使用常规的std::sort(first, last, compare),并编写以下类似的比较函数:

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

这个 compareLen 对我不起作用。我已经使用了你的函数,并通过以下代码行调用它: sort(words.begin(), words.end(), compareLen); - Ganesh M S

2

std::sort 接受一个可选参数,用于自定义比较

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

你可以定义一个根据长度进行比较的函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接