hi... i need to sort a vector by particular class member variable... how do i do that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Example{
private:
string name;
...
public:
string getName(){return name;}
void setName(string input){name = input;}
...
};
int main(){
vector<Example> myVec;
vector<Example>::iterator myIt;
...
sort(....); //what must i write in this statement to make it sort by the name of all the example objs?
...
}
The second prototype includes a comparison function
1 2
template <class RandomAccessIterator, class Compare>
void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
Write yourself a little function that will compare two Examples based upon the name.
1 2 3 4
booloperator compare_examples ( const Example& a, const Example& b )
{
return a.getName() < b.getName();
}
You can also just overload the < operator directly (replace the word "compare_examples" in the above example with "<").
You will also have to change the getName to be const-correct: string getName() const { return name; }
(this is a requirement for the sort() algorithm --which deals with const object references, if I remember correctly).
Now you can sort() on the name, either by explicitly specifying a comparison function name, or by using the implicit, overloaded < operator.