Page 1 of 1

Sorting vector

Posted: Wed Apr 07, 2004 8:25 pm
by Dominik Michniewski
Maybe exist topic, which contains such question (in this case I apologize for posting next one ...), but I want help from someone who is familiar with vector sorting.
I have such problem:

this piece of code causes compile error. Could anyone tell me why and how can I avoid this error (I've compiled it using VC6 without errors and warnings):

Code: Select all

#include <vector>
#include <algorithm>

class CHAIN
{
public:
	int a,b,c;

	int operator<(const CHAIN &s)
	{
		/* doing something, never mind what ;-) */
		return 1;
	}
};

typedef std::vector<CHAIN> ChainVector;

using namespace std;

int main(void)
{
	ChainVector v;

	v.resize(0);
	/* read data into vector */
	...
	sort(v.begin(),v.end()); // <- this line causes error, see below
	...
	return 0;
}
The error is: cannot pass argument to operator< function ... (Of course it's not exactly message, but I don't have now it :( ). I think that I made some small mistake in this function, but I don;t know which ? maybe I wrote incorrect header ...

Best regards
DM

Posted: Wed Apr 07, 2004 9:36 pm
by UFP2161
You can write it inside the class like:
[cpp]bool operator< (const CHAIN &s) const
{
...
}[/cpp]

or outside the class like:
[cpp]bool operator< (const CHAIN &s, const CHAIN &t)
{
...
}[/cpp]

Basically, the STL sort function is looking for a function that takes two variables that have the const flag, i.e. won't be changed by the function. I believe the const construction in the former case tells the compiler to make the this variable a const.

Posted: Thu Apr 08, 2004 8:01 am
by Dominik Michniewski
Thanks UFP2161 for quick answer ... I forgot about word 'const' after the class member function :oops:
I think that was my problem :)

Best regards
DM