On Feb 19, 1:39 pm, spl <splender....@gmail.com> wrote:
> I have an array of objects. I want to sort the array of a
> given numeric value that exists in each of the objects. Suppose the
> array of objects is called student and the numeric value I want to
> sort the array based on the member is called "rollno".
> ex:
> class student{
> int rollno;
> int name;
> int status;};
>
> student obj[10]
> here, I have to sort obj of 10objects, based on rollno.
>
> Please give your suggestion for any fast method?
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class student{
public:
// added c-tor
student(int r,int n, int s):rollno(r),name(n),status(s) { }
int getRollno() const { return rollno;}
int getName() const { return name;}
int getStatus() const { return status;}
private:
int rollno;
int name;
int status;
};
bool compare(const student& x, const student& y) {
return x.getRollno() < y.getRollno();
}
int main(){
vector<student> students;
student s1(10,20,30);
student s2(40,50,60);
student s3(25,85,9

;
students.push_back(s1);
students.push_back(s2);
students.push_back(s3);
sort(students.begin(),students.end(),compare);
for(vector<student>::const_iterator iter=students.begin();
iter!=students.end();++iter)
std::cout << (*iter).getRollno() << '\t' << (*iter).getName() <<
'\t' << (*iter).getStatus() << '\n';
return 0;
}
Hope this helps a bit,
Rgds,
Here is a very primitive example with the compare that you can supply
to the STL sort