Reputation: 317
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. The regular sort function did not solve my problem. Can someone point out how to do this? I want the output as 345366,38239,029323. I want the leading zero in 029323 as well.
#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;
}
Upvotes: 0
Views: 1165
Reputation: 8564
You can use a comparator function like this:
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.
Edit: From the comments, it seems std::stoi()
is much better than std::atoi()
. For converting C++ strings, use 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.
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):
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.
Upvotes: 4