Sorting vector

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Sorting vector

Post 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
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)
UFP2161
A great helper
Posts: 277
Joined: Mon Jul 21, 2003 7:49 pm
Contact:

Post 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.
Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Post 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
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)
Post Reply

Return to “C++”