"news.hku.hk" <bi******@hkusua.hku.hk> writes:
i have a array of objects from the class job, i.e.
job teacher[1]
job teacher[2]
job teacher[3]
............until job teacher[100]
these objects contain the string name of the teachers and
teacher[1].showname(); //return string "Sam Clinton"
teacher[2].showname(); //return string "John Patten"
teacher[3].showname(); //return string "John Dickens"
........ and so on........
i would like to output to screen in ascending order of teacher's name, i.e.
John Dickens
John Patten
Sam Clinton
What should i do? which kind of sorting is better, i don't know any of
them.....
Try the most standard sort first. The example below isn't quite what you
want, but it shows how to use sort with user-defined types like your
"job".
#include <deque>
#include <algorithm>
#include <iostream>
using namespace std;
class simple {
public:
int value;
// redefine the '<' operator, so when 2 simple objects are
// compared, the 'value' fields of the objects are compared.
const bool operator<(const simple &rhs) const
{ return this->value < rhs.value; }
};
int main()
{
deque<simple> Q; // An empty, elastic, container.
simple s;
s.value=0;
Q.push_back(s);
s.value=2;
Q.push_back(s);
s.value=1;
Q.push_back(s);
for(int i=0;i<Q.size(); i++){
cout << Q[i].value; cout << " ";
}
cout <<endl;
// Output: 0 2 1
// Now let's sort! sort uses the '<' operator that we created in the 'simple' class
sort(Q.begin(), Q.end());
for(int i=0;i<Q.size(); i++){
cout << Q[i].value; cout << " ";
}
cout <<endl;
// Output: 0 1 2
}