Blog Archive

Tuesday, July 10, 2018

Sorting a vector of custom objects

Reference:
Link
Question: Sorting a vector of custom objects

Answer:


#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

struct less_than_key
{
    inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
    {
        return (struct1.key < struct2.key);
    }
};


struct less_than_keyP
{
    inline bool operator() (const MyStruct * struct1, const MyStruct * struct2)
    {
        return (struct1->key < struct2->key);
    }
};



int main(){

std::vector < MyStruct > vec;
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
std::vector < MyStruct *> vecp;
vecp.push_back(&vec[0]);
vecp.push_back(&vec[1]);
vecp.push_back(&vec[2]);
vecp.push_back(&vec[3]);
//std::sort(vec.begin(),  vec.end(),  less_than_key());
std::sort(vecp.begin(), vecp.end(), less_than_keyP());

for(int i=0;i<4;i++){
    cout<<"vecp:" <<  (*vecp[i]).key << " " << vecp[i]->stringValue << endl;
    cout<<"vec:"  <<  vec[i].key << " " << vec[i].stringValue << endl;

}
cout << " ====" << endl;
std::sort(vec.begin(),  vec.end(),  less_than_key());
//std::sort(vecp.begin(), vecp.end(), less_than_keyP());

for(int i=0;i<4;i++){
    cout<<"vecp:" <<  (*vecp[i]).key << " " << vecp[i]->stringValue << endl;
    cout<<"vec:"  <<  vec[i].key << " " << vec[i].stringValue << endl;

}


}

//result:

vecp:1 this
vec:4 test
vecp:2 is
vec:3 a
vecp:3 a
vec:2 is
vecp:4 test
vec:1 this
====
vecp:4 test
vec:1 this
vecp:3 a
vec:2 is
vecp:2 is
vec:3 a
vecp:1 this
vec:4 test

No comments:

Post a Comment