Is there a way to sort a vector with a class that has an int variable? I want to have my vector sorted and printed in console. I want to be able to sort the vectors.

Say i create a bunch of vectors here on user input vector<PCB> Disks2[DiskDevices];

Basically if i choose vector<PCB> Disks2[1]; itll sort 1 if i choose vector<PCB> Disks2[2]; itll sort 2 based on the Cylinder in the class.

And i have this class

class PCB
{
public:
    void setPID (int a)
    {
        PID = a;
    }
    int retrievePID()
    {
        return PID;
    }
    void setFilename (string input)
    {
        Filename = input;
    }
    string retrieveFilename()
    {
        return Filename;
    }
    void setMemstart (int a)
    {
        Memstart = a;
    }
    int retrieveMemstart()
    {
        return Memstart;
    }
    void setRW (char a)
    {
        rw = a;
    }
    char retrieveRW()
    {
        return rw;
    }
    void setFilelength (int input)
    {
        Filelength = input;
    }
    int retrieveFilelength()
    {
        return Filelength;
    }
    int retrieveCylinder()
    {
        return Cylinder;
    }
    void setCylinder (int a)
    {
        Cylinder = a;
    }

private:
    int PID;
    string Filename;
    int Memstart;
    char rw;
    int Filelength;
    int Cylinder;
};

How can i sort that vector based on the Cylinder int? I want the Vector to organize the order of the information based on Cylinder? Is this possible? I cant figure it out.

Edited 2 Years Ago by mystycs

Yes, it is possible. You will have to overload the less-than operator in your PCB class.

The results of the sort depends on how you implement the < operator.

Add the following to your PCB class definition (header file):

bool operator<( const PCB& other ) const;

Now implement the code (in your cpp file):

bool PCB::operator<( const PCB& other ) const
{
    return other.Cylinder < this.Cylinder;
}

Aftwards, just call the std::sort function on your vector of PCB objects.

If for some reason you can't or don't want to implement operator<, for example it is already implemented to do something else you can always use the 2nd form of std::sort

template <class RandomAccessIterator, class Compare>
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

Which takes 3 parameters the 3rd one being a comparison functor (or function) that embodies your sort algorithm (i.e. compares 2 objects and decideds which is smaller).

Can you explain a little more about your intended design, please? This looks a like a control block for a file handle, but just what you mean to do with it isn't clear.

If it needs to be sorted all the time, then a priority_queue<> as described in the other thread may still be the right approach; either way, you would need to define a comparison function or operator.

This article has been dead for over six months. Start a new discussion instead.