Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Sorting strings

47 views
Skip to first unread message

udt...@gmail.com

unread,
May 18, 2015, 12:45:19 AM5/18/15
to
I would like to have sort function for strings that would first compare length and have longer string be greater then shorter one, and if they are same length - compare them as usual. So that

1. "1234567"
2. "12345"
3. "111111"
4. "13456"
5. "01102121"

would get sorted as
5 > 1 > 3 > 4 > 2

bool less(const string& lhs, const string&rhs)
{
// if( lhs.length() < rhs.length() ) return true;
return (lhs.length() < rhs.length()) ? true : (lhs < rhs);
}

Is there a more efficient way to do this ?

Thank you dear newsgroup.

Öö Tiib

unread,
May 18, 2015, 2:16:26 AM5/18/15
to
On Monday, 18 May 2015 07:45:19 UTC+3, udt...@gmail.com wrote:
> I would like to have sort function for strings that would first
> compare length and have longer string be greater then shorter one, and
> if they are same length - compare them as usual. So that
>
> 1. "1234567"
> 2. "12345"
> 3. "111111"
> 4. "13456"
> 5. "01102121"
>
> would get sorted as
> 5 > 1 > 3 > 4 > 2
>
> bool less(const string& lhs, const string&rhs)
> {
> // if( lhs.length() < rhs.length() ) return true;
> return (lhs.length() < rhs.length()) ? true : (lhs < rhs);
> }

So both 'less( "1234567", "13456" )' and
'less( "13456", "1234567" )' return 'true'?

> Is there a more efficient way to do this ?

Why you care about efficiency when your algorithm seems incorrect?
Most important goal is always correctness since no one needs
software that gives incorrect answers more quickly.

Juha Nieminen

unread,
May 18, 2015, 5:46:29 AM5/18/15
to
udt...@gmail.com wrote:
> bool less(const string& lhs, const string&rhs)
> {
> // if( lhs.length() < rhs.length() ) return true;
> return (lhs.length() < rhs.length()) ? true : (lhs < rhs);
> }

That doesn't work because if lhs is larger than rhs, then they won't
be compared by length. What you want is:

return (lhs.length() == rhs.length()) ? (lhs < rhs) :
(lhs.length() < rhs.length());

The compiler will most probably optimize those extra length() calls
away, so there's usually no need to worry about them. (And even if it
doesn't, it's not a big deal anyway.)

--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---
0 new messages