基于字符串大小排序字符串向量 [英] sorting a string vector based on the string size

查看:122
本文介绍了基于字符串大小排序字符串向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何对字符串向量进行排序,使字符数量最少的字符串在向量的顶部。例如,如果向量在其中具有ABCD,ABCDE,ABC。 ABC到顶部。我有兴趣知道如何可以通过sort_if和什么样的谓词来实现?任何其他方法也受欢迎

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

这篇关于基于字符串大小排序字符串向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆