Fastest way to sort a list of number and their index

前端 未结 8 1151
萌比男神i
萌比男神i 2021-02-14 21:15

I have a question that could seem very basic, but it is in a context where \"every CPU tick counts\" (this is a part of a larger algorithm that will be used on supercomputers).<

8条回答
  •  借酒劲吻你
    2021-02-14 21:36

    The obvious starting point would be a structure with operator< defined for it:

    struct data { 
        unsigned long long int number;
        size_t index;
    };
    
    struct by_number { 
        bool operator()(data const &left, data const &right) { 
            return left.number < right.number;
        }
    };
    

    ...and an std::vector to hold the data:

     std::vector items;
    

    and std::sort to do the sorting:

     std::sort(items.begin(), items.end(), by_number());
    

    The simple fact is, that the normal containers (and such) are sufficiently efficient that using them doesn't make your code substantially less efficient. You might be able to do better by writing some part in a different way, but you might about as easily do worse. Start from solid and readable, and test -- don't (attempt to) optimize prematurely.

    Edit: of course in C++11, you can use a lambda expression instead:

    std::sort(items.begin(), items.end(), 
              [](data const &a, data const &b) { return a.number < b.number; });
    

    This is generally a little more convenient to write. Readability depends--for something simple like this, I'd say sort ... by_number is pretty readable, but that depends (heavily) on the name you give to the comparison operator. The lambda makes the actual sorting criteria easier to find, so you don't need to choose a name carefully for the code to be readable.

提交回复
热议问题