Thursday 12 September 2013

re-order vector given a vector

re-order vector given a vector

I have a vector<std::unique_ptr<X>> and a vector<const X*> that contain
the same set of pointers, but in a different order. I want to have the
vector of unique pointers be ordered exactly like the vector of const
pointers.
One way I could do it is like this:
vector<std::unique_ptr<X>> uniq_ptrs;
vector<const X*> const_ptrs;
vector<std::unique_ptr<X>> tmp(uniq_ptrs.size());
hash_map<const X*, int> indices;
for (int i = 0; i < const_ptrs->size(); ++i) {
indices[const_ptrs[i]] = i;
}
for (std::unique_ptr<X>& uniq_ptr : uniq_ptrs) {
tmp[indices[uniq_ptr.get()]].swap(uniq_ptr);
}
uniq_ptrs.swap(tmp)
an in-place version, still with hash_map:
vector<const X*> const_ptrs;
hash_map<const X*, int> indices;
for (int i = 0; i < const_ptrs.size(); ++i) {
indices[const_ptrs[i]] = i;
}
for (int i = 0; i < const_ptrs.size(); ++i) {
std::swap(uniq_ptrs[i], uniq_ptrs[indices[const_ptrs[i]]]);
}
But I hope there is a nicer way that doesn't involve a temporary vector a
hash map and two passes over the data.

No comments:

Post a Comment