jeudi 21 mars 2019

C++: Sort a vector

In the below C++ snippet,

HOW TO SORT the vector "TwoIntsVec" BASED ON the element "int a" in TwoInts struct. i.e. i need to place the "TwoIntsVec[i] which has the least "TwoIntsVec[i].a" in the 1st place and so on in increasing order of "TwoIntsVec[i].a".

In the below example the vector elemnt struct having 7,3 should be placed 1st as 7 is the least "a" and so on.

struct TwoInts
{
    int a;
    int b;
};

void PushToVector(int a, int b, std::vector<TwoInts>& TwoIntsVec)
{
    TwoInts temp;
    temp.a = a;
    temp.b = b;
    TwoIntsVec.push_back(temp);
}

int main()
{
    std::vector<TwoInts> TwoIntsVec;
    PushToVector(21,3,TwoIntsVec);
    PushToVector(7,3,TwoIntsVec);
    PushToVector(12,3,TwoIntsVec);
    PushToVector(9,3,TwoIntsVec);
    PushToVector(16,3,TwoIntsVec);

    // Below sort would NOT work here, as TwoIntsVec is
    // not a std::vector<int>
    std::sort( TwoIntsVec.begin(),  TwoIntsVec.end()); 

   // HOW TO MAKE THE SORT BASED ON the element "int a" in 
   TwoInts struct



}

Aucun commentaire:

Enregistrer un commentaire