Czesc, mam pytanie: sortujac np. wektor obiektow mozemy skorzystac z std::sort + przeciazajac operator(). A w jakis sposob mozna zaimplementowac wlasna metode sortowania - np quick sort dla takiego wektora ?
Dajmy na to jakis moj stary program (to tylko przyklad wiem ze zle napisany).
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
const unsigned numberOfPeople = 3;
using namespace std;
struct Person {
string name;
int age;
string favoriteColor;
};
struct Compare_functor {
bool operator()(const Person &first, const Person & second){
return first.age < second.age;
}
}myobject;
int main()
{
vector<Person> people(numberOfPeople);
for (vector<Person>::size_type i = 0; i != numberOfPeople; ++i) {
cout << "Person #" << i + 1 << " name: ";
cin >> people[i].name;
cout << "Person #" << i + 1 << " age: ";
cin >> people[i].age;
cout << "Person #" << i + 1 << " favorite color: ";
cin >> people[i].favoriteColor;
}
cout << "\n\n";
sort(people.begin(), people.end(), myobject);
for (unsigned i = 0; i < people.size(); ++i)
cout << people[i].age << " ";
cout << endl;
return 0;
}
Dla napisania wlasnego quick sort musialbym skorzystac np z:
void quickSort(vector<int> &input, int left, int right)
{
int i=left, j=right;
int pivot = input[(i+j)/2];
// partition
while (i <= j) {
while (input[i] < pivot)
i++;
while (input[j] > pivot)
j--;
if (i <= j) {
int tmp = input[i];
input[i] = input[j];
input[j] = tmp;
i++;
j--;
}
}
// recursion
if (left < j)
quickSort(input, left, j);
if (i < right)
quickSort(input, i, right);
}
I przedefiniowac wszystkie potrzebne operatory dla mojej klasy ?
Moze glupie pytanie ale dawno nie uzywalem c++ a musze rozwiazac takie problem.