-
Vector Sort C++
hey guys,
I need a little help. I have a vector of objects, each object has a name and an age variable. I want to be able to sort the vector by each objects age. Google brings up alot of results but I don't really understand most of them. This is what I've got so far. (might be some syntax mistakes, not a copy and paste job)
Class people{ string name, int age..... }
vector<people> vec;
bool SortMethod (const people& person1, const people& person2) const
{ return person1.getage() < person2.getage(); }
void Sort()
{
(vec.begin(), vec.end(), SortMethod);
}
Now according to all the threads I've read this is how to do it but it doesn't seem to do anything. Little help please. Thanks.
-
Re: Vector Sort C++
How big is the vector going to be? My mind's not in a place where it can deal with C++ right now, but by the looks of it that's going to be Bubble Sort - which be slow! Still, not a problem if it's not many entries.
-
Re: Vector Sort C++
About 10 objects in the vector
-
Re: Vector Sort C++
Firstly, define a comparator for sorting (as you have done with SortMethod). As well as defining a function, you can also define an object to do the same job:
Code:
struct AgeComparator {
bool operator() (const People & first, const People & second) {
return first.getage() < second.getage();
}
} ageComparator;
Then, where you want to sort the vector:
Code:
sort(vec.begin(), vec.end(), ageComparator);
-
Re: Vector Sort C++
Not using a list instead?
http://www.cplusplus.com/reference/stl/list/sort/
Not sure why you are using a vector tbh
-
Re: Vector Sort C++
Actually a vector would be better for things like quick sort, because of the random access ability.
a List is not designed to allow simple random access.
-
Re: Vector Sort C++
Tbh I only used vectors because that is what I was most familiar with, they do the job for what I need them for anyways
Haven't been able to try out mike_w's code yet but I'll give it a go later on today
Thanks for all the replies anyways guys