Suppose I have some data stored in a container of unique_ptrs:
struct MyData {
int id; // a unique id for this particular instance
data some_data; // arbitrary additional data
};
// ...
std::vector<std::unique_ptr<MyData>> my_data_vec;
The ordering of my_data_vec is important. Suppose now I have another vector of IDs of MyDatas:
std::vector<int> my_data_ids;
I now want to rearrange my_data_vec such that the elements are in the sequence specified by my_data_ids. (Don’t forget moving a unique_ptr requires move-semantics with std::move().)
What’s the most algorithmically efficient way to achieve this, and do any of the STL algorithms lend themselves well to achieving this? I can’t see that std::sort would be any help.
Edit: I can use O(n) memory space (not too worried about memory), but the IDs are arbitrary (in my specific case they are actually randomly generated).
my_data_ids.std::unique_ptr<MyData>based on their ID’s index in that map.std::sortto sort themy_data_vecusing that function object.Here’s a sketch of this:
If memory is scarce, but time doesn’t matter, you could do away with the map and search the IDs in the
my_data_idsvector for each comparison. However, you would have to be really desperate for memory to do that, since two linearly complex operations per comparison are going to be quite expensive.