Sort the strings based on their numeric values

Q

qazmlp

I have got the following strings:
121721234567890
13
1217212345
129

Is it possible to do descending sort for these strings based on their
numeric values?

After sorting, they need to figure in this order:
121721234567890
1217212345
129
13

This seems to be bit difficult for me with std::sort().

Could you help?
 
J

John Harrison

qazmlp said:
I have got the following strings:
121721234567890
13
1217212345
129

Is it possible to do descending sort for these strings based on their
numeric values?

After sorting, they need to figure in this order:
121721234567890
1217212345
129
13

This seems to be bit difficult for me with std::sort().

Could you help?

Its as easy with std::sort as any other way. All you need to do is write a
function that compares based on the numeric value of the string, then you
can plug that function into std::sort

bool NumericGreaterThan(const std::string& lhs, const std::string& rhs)
{
...
}

std::sort(x.begin(), x.end(), NumericGreaterThan);

Of course writing NumericGreaterThan might be a bit of a challenge.

john
 
E

Ed

John Harrison said:
Of course writing NumericGreaterThan might be a bit of a challenge.

bool NumericGreaterThan(const std::string& lhs, const std::string& rhs)
{
return atoi(lhs.cstr())>atoi(rhs.c_str());
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top