Alphabetical sort of vector - struct.

Hello again cplusplus.com!

As the title suggests, I'm trying to sort a vector by the std::string name within a struct.

But I've run in to a problem that I don't know how to fix. The program compiles and runs fine, until it hits the following line:
std::sort( table.begin(), table.end(), compareByWord );

Which gives me the error:
Expression: invalid operator< 


This is my struct:
1
2
3
4
5
6
struct tableInfo
{
	std::string name;
	std::string info;
	std::string link;
};


This is the function compareByWord:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool compareByWord( const tableInfo &lhs, const tableInfo &rhs )
{
	unsigned int length = lhs.name.length();

	if( rhs.name.length() < length )
		length = rhs.name.length();

	int sameLetters = 0;

	for( unsigned int i = 0; i < length; ++i )
	{
		if( sameLetters == length )
			return false;

		if( tolower( lhs.name[ i ] ) == tolower( rhs.name[ i ] ) )
		{
			++sameLetters;
			continue;
		}

		if( lhs.name[ i ] < rhs.name[ i ] )
			return true;
	}

	return false;
}


I've run debug on the program, the function seems to run fine the whole way through.
Pressing F10( Step Over, VS2012 ), takes me to xutility and shows me this template, which is when the error pops up, on line 9:
1
2
3
4
5
6
7
8
9
10
11
template<class _Pr, class _Ty1, class _Ty2> inline
	bool _Debug_lt_pred(_Pr _Pred,
		_Ty1& _Left, _Ty2& _Right,
		_Dbfile_t _File, _Dbline_t _Line)
	{	// test if _Pred(_Left, _Right) and _Pred is strict weak ordering
	if (!_Pred(_Left, _Right))
		return (false);
	else if (_Pred(_Right, _Left))
		_DEBUG_ERROR2("invalid operator<", _File, _Line);
	return (true);
	}


If possible. Could someone please tell me what's going wrong? Been searching the internet for a while now.
Thanks for any help! (:
Last edited on
wow, and just like that! It works!

I changed lines 21 and 22 in compareByWord, to:
return ( lhs.name[ i ] < rhs.name[ i ] );
Last edited on
Shouldn't your compareByWord function return a full statement like :
(lhs.name[ i ] < rhs.name[ i ]) or (lhs.name[ i ] > rhs.name[ i ])

(The Sort() example from the resources seams to work like that, and when I tried to return true from their example I got the same error)
http://www.cplusplus.com/reference/algorithm/sort/
Last edited on
It's a bool function.

so;
return 1 < 3;

Would be true. (:

Edit:
It must have something to do with the sort, binary predicate. I'm not sure. I've never used sort with 3 parameters before today! lol.

http://msdn.microsoft.com/en-us/library/ecdecxh1(v=vs.80).aspx
Last edited on
Topic archived. No new replies allowed.