[英]How do I sort a vector of strings in descending order?
I have this following code where there is a vector of strings.我有以下代码,其中有一个字符串向量。 Each string is an integer. I want to sort this in a descending order.
每个字符串都是一个 integer。我想按降序对其进行排序。 The regular sort function did not solve my problem.
常规排序 function 并没有解决我的问题。 Can someone point out how to do this?
有人可以指出如何做到这一点吗? I want the output as 345366,38239,029323.
我想要 output 作为 345366,38239,029323。 I want the leading zero in 029323 as well.
我也想要 029323 中的前导零。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main() {
vector<string> v = {"345366", "029323", "38239"};
vector<int> temp(v.size());
for (int idx = 0; idx < v.size(); idx++)
temp[idx] = stoi(v[idx]);
sort(temp.begin(), temp.end()));
cout<<temp[0]<<" "<<temp[1]<<" "<<temp[2];
return 0;
}
You can use a comparator function like this:您可以像这样使用比较器 function:
vector<string> v = {"345366", "029323", "38239"};
std::sort(v.begin(), v.end(), [](const std::string &s1, const std::string &s2) -> bool {
return std::stoi(s1) > std::stoi(s2);
});
for(auto i : v)
cout << i << endl;
Check this std::stoi() reference .检查此 std::stoi() 参考。
Edit: From the comments, it seems std::stoi()
is much better than std::atoi()
.编辑:从评论来看,似乎
std::stoi()
比std::atoi()
好得多。 For converting C++ strings, use std::stoi()
.要转换 C++ 字符串,请使用
std::stoi()
。 For C strings, std::atoi()
will silently fail without generating any error if the string is not convertible to int, whereas std::stoi()
will generate an exception, thus is a safer choice as well.对于 C 字符串,如果字符串不可转换为 int,
std::atoi()
将静默失败而不会产生任何错误,而std::stoi()
将产生异常,因此也是一个更安全的选择。
cout << std::atoi("abc") << endl; // runs smoothly
cout << std::stoi("abc") << endl; // creates an 'uncaught exception of type std::invalid_argument: stoi'
However, the results will be the same in this case (will extract the prefix integer part and exit, in case of std::stoi()
, if the string doesn't begin with integers, it will create an exception):但是,在这种情况下结果将是相同的(将提取前缀 integer 部分并退出,如果是
std::stoi()
,如果字符串不以整数开头,它将创建一个异常):
cout << std::atoi("999abc12") << endl; // prints 999
cout << std::stoi("999abc12") << endl; // prints 999
cout << std::stoi("abcdef12") << endl; // generates exception
Also see this answer .另请参阅此答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.