简体   繁体   中英

what is the fastest way of sorting a vector?

I want to sort the "mystruct" by the distance variable, what is the fastest way of doing this?

struct MyStruct {
   int scale;
   bool pass;
   float distance;
};
vector<MyStruct> mystruct;
...
sort (mystruct.begin(), mystruct.begin() + mystruct.size());
//this doesn't work since is trying to sort by "MyStruct" and not by a number

if I had a

vector<float> myfloat;
...
sort (myfloat.begin(), myfloat.begin() + myfloat.size());

then will work perfectly.

You need to write your own operator< for your struct.

It should be something like

bool operator<( const MyStruct& s1, const MyStruct& s2 )
{
    // compare them somehow and return true, if s1 is less than s2
    // for your case, as far as I understand, you could write
    // return ( s1.distance < s2.distance );
}

The other option is to write a functional object, but it's not that necessary here, writing operator< is easier (for beginners)

You need to provide either a functor to the sort function, or a less than operator:

struct MyStruct_Compare {
    bool operator()(const MyStruct& a, const MyStruct& b) {
        return a.distance < b.distance;
    }
}

std::sort(mystruct.begin(), mystruct.end(), MyStruct_Compare());

OR:

bool operator<(const MyStruct& a, const MyStruct& b) {
    return a.distance < b.distance;
}

std::sort(mystruct.begin(), mystruct.end());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM