sort a vector

Hi all,
I have a vector,the type of the element within it is list<int>,and i wanna sort this vector.So i implemented a function as a predicate for sort(the STL algorithm).Problem came when i missed the bold part in my code,g++ generated lots of error messages.And after i added the bold part,the code compiled successfully.Why?(As i know,the predicate need not to have a const parameter)Any tips will be appreciated.Thanks.
Dengjin.

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>

using namespace std;

void print(list<int>& lst)
{
	copy(lst.begin(),lst.end(),
			ostream_iterator<int>(cout," "));
	cout<<endl;
}

bool sortCritic(const list<int>& lst1,const list<int>& lst2)
{
	return lexicographical_compare(lst1.begin(),lst1.end(),
											 lst2.begin(),lst2.end());
}

int main()
{
	list<int> c1,c2,c3,c4;
	
	for(int i=1;i<=5;i++)
		c1.insert(c1.end(),i);

	c4 = c3 = c2 = c1;

	c1.push_back(7);	
	c3.push_back(2);
	c3.push_back(0);
	c4.push_back(2);

	vector<list<int> > cc;

	cc.push_back(c1);
	cc.push_back(c2);
	cc.push_back(c3);
	cc.push_back(c4);

	for_each(cc.begin(),cc.end(),print);
	sort(cc.begin(),cc.end(),sortCritic);
	cout<<endl;
	for_each(cc.begin(),cc.end(),print);
	
}


The objects don't have to be const, it's enough that your function treats them as such; it's a safety feature. The references being const stops you from writing any members, and prevents you from calling any members or operators that aren't also const. You really don't want to be changing your data during a sort, especially when using the original, not a copy!

1 Like

you're right,error went away without using reference.Thanks

You should be using references though! Otherwise it creates a copy ever time which is very slow. You just have to make it a const reference.

1 Like

yeahgot it:)