std::string operator< ?

M

Matthias

Now I am confused.
I am doing a "less" comparison in my program between strings, to see
which strings in some range precede others.
This is my approach:

class SortedByName
{
public:
bool operator() (const boost::filesystem::path& lhs,
const boost::filesystem::path& rhs) {
std::string path1 = lhs.leaf();
std::string path2 = rhs.leaf();
boost::algorithm::to_lower( path1 );
boost::algorithm::to_lower( path2 );
return path1 < path2;
}
};

Now, there are at least two questions coming to my mind:

1. How does operator< work on strings? I wanted to look it up in my C++
implementation doc, but it doesn't exist in the std::basic_string
reference! (the comparison works by the way).

2. Meyers has an own item in his STL book which is dedicated to exactly
this topic. He doesn't even mention an operator< to do the comparison,
but suggests to use lexicographical_compare, which however would need me
to supply a (correct and portable) comparison predicate for characters.

What's the deal?
 
M

Matthias

Matthias said:
1. How does operator< work on strings? I wanted to look it up in my C++
implementation doc, but it doesn't exist in the std::basic_string
reference! (the comparison works by the way).

I found the reason why it was not listed. The global operator< will be
used, and it will invoke std::basic_string::compare.
But Meyers doesn't mention this function either. So question #2 is still
valid :)
 
I

Ioannis Vranos

Matthias said:
I found the reason why it was not listed. The global operator< will be
used, and it will invoke std::basic_string::compare.
But Meyers doesn't mention this function either. So question #2 is still
valid :)


The two comparisons below are equivalent. No predicate is required for char.


#include <string>
#include <iostream>
#include <ostream>
#include <algorithm>


int main()
{
using namespace std;

string s1="string1";

string s2="string2";

cout<<(s1<s2)<<endl;

cout<<lexicographical_compare(s1.begin(), s1.end(), s2.begin(),
s2.end())
<<endl;
}
 
M

Matthias

Ioannis said:
The two comparisons below are equivalent. No predicate is required for
char.


#include <string>
#include <iostream>
#include <ostream>
#include <algorithm>


int main()
{
using namespace std;

string s1="string1";

string s2="string2";

cout<<(s1<s2)<<endl;

cout<<lexicographical_compare(s1.begin(), s1.end(), s2.begin(),
s2.end())
<<endl;
}

And what comparison function does lexicographical_compare use by
default? Is it portable? I'm just wondering why Meyers would encourage
you to write your own, if it isn't necessary.
 

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

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top