Sort by proxy (or: sort one container by the contents of another) in C++

前端 未结 7 866
失恋的感觉
失恋的感觉 2020-12-19 02:34

I have a set of data which is split into two arrays (let\'s call them data and keys). That is, for any given item with an index i, I c

相关标签:
7条回答
  • 2020-12-19 03:29

    Create a vector of objects that contain indices to the two arrays. Define operator< for that object to do the comparison based on keys[index]. Sort that vector. When you're done, walk through that vector and put your original objects into the order defined by those proxy objects:

    // warning: untested code.
    struct sort_proxy { 
        size_t i;
    
        bool operator<(sort_proxy const &other) const { 
            return keys[i] < keys[other.i];
        }
    };
    
    // ... key_size = number of keys/data items.
    std::vector<sort_proxy> proxies(key_size); 
    
    for (i=0; i<keys_size; i++)
        proxies[i].i = i;
    
    std::sort(proxies.begin(), proxies.end());
    
    // in-place reordering left as an exercise for the reader. :-)
    for (int i=0; i<proxies[i].size(); i++) {
        result_keys[i] = keys[proxies[i].i];
        result_data[i] = data[proxies[i].i];
    }
    
    0 讨论(0)
提交回复
热议问题