根据字符串大小对字符串向量进行排序
sorting a string vector based on the string size
我想知道如何对字符串向量进行排序,以便字符数最少的字符串位于向量之上。例如,如果向量中有 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 );
您可以只定义一个基于长度进行比较的函数。
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 在将字符串放入字符串向量时遇到问题?
- 如何从字符串向量构造对象并避免复制?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 将字符串向量中的字符串放入主字符串中
- 如何在 c++ 中从字符串向量中读取
- 用字符串的向量分配字符串向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- C++ 中字符串向量的索引
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何从输入中获取字符串向量?
- 使用 C++-17,如何从字符串向量填充元组
- 对于循环增量器不能用作字符串向量的索引
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 如何从字符串向量中选择第 n 个位置?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 反转不带反转函数的字符串向量
- 如何在字符串向量中指向const int
- 如何在字符串向量中找到某个值