Fastest way to sort a list of number and their index

前端 未结 8 1143
萌比男神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:39

    std::pair and std::sort fit your requirements ideally: if you put the value into the pair.first and the index in pair.second, you can simply call a sort on a vector of pairs, like this:

    // This is your original data. It does not need to be in a vector
    vector orig;
    orig.push_back(10);
    orig.push_back(3);
    orig.push_back(6);
    orig.push_back(11);
    orig.push_back(2);
    orig.push_back(19);
    orig.push_back(7);
    // This is a vector of {value,index} pairs
    vector > vp;
    vp.reserve(orig.size());
    for (size_t i = 0 ; i != orig.size() ; i++) {
        vp.push_back(make_pair(orig[i], i));
    }
    // Sorting will put lower values ahead of larger ones,
    // resolving ties using the original index
    sort(vp.begin(), vp.end());
    for (size_t i = 0 ; i != vp.size() ; i++) {
        cout << vp[i].first << " " << vp[i].second << endl;
    }
    

提交回复
热议问题