Reorder vector using a vector of indices

前端 未结 14 1941
耶瑟儿~
耶瑟儿~ 2020-11-28 06:15

I\'d like to reorder the items in a vector, using another vector to specify the order:

char   A[]     = { \'a\', \'b\', \'c\' };
size_t ORDER[] = { 1, 0, 2 }         


        
14条回答
  •  广开言路
    2020-11-28 06:34

    It's an interesting intellectual exercise to do the reorder with O(1) space requirement but in 99.9% of the cases the simpler answer will perform to your needs:

    void permute(vector& values, const vector& indices)  
    {   
        vector out;
        out.reserve(indices.size());
        for(size_t index: indices)
        {
            assert(0 <= index && index < values.size());
            out.push_back(values[index]);
        }
        values = std::move(out);
    }
    

    Beyond memory requirements, the only way I can think of this being slower would be due to the memory of out being in a different cache page than that of values and indices.

提交回复
热议问题