假设我有一些数据存储在 unique_ptr
的容器中:
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;
my_data_vec
的顺序很重要。假设现在我有另一个 MyDatas ID 向量:
std::vector<int> my_data_ids;
我现在想要重新排列 my_data_vec
,使元素按照 my_data_ids
指定的顺序排列。 (不要忘记移动 unique_ptr
需要使用 std::move()
进行移动语义。)
实现此目的最有效的算法方法是什么,并执行以下任一操作: STL 算法很适合实现这一目标?我看不出 std::sort
有任何帮助。
编辑:我可以使用 O(n) 内存空间(不太担心内存),但 ID 是任意的(在我的具体情况下,它们实际上是随机生成的)。
Suppose I have some data stored in a container of unique_ptr
s:
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).
发布评论
评论(3)
my_data_ids
中的索引。std::unique_ptr
。std::sort
使用该函数对象对my_data_vec
进行排序。这是一个示意图:
如果内存不足,但时间并不重要,您可以放弃映射并在每次比较时在
my_data_ids
向量中搜索 ID。但是,您必须非常需要内存才能做到这一点,因为每次比较两个线性复杂的操作将非常昂贵。my_data_ids
.std::unique_ptr<MyData>
based on their ID's index in that map.std::sort
to sort themy_data_vec
using 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_ids
vector 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.为什么不尝试将数据移至 STL Set 中?您只需要实现比较功能,很快就会得到一组完美排序的数据。
Why don't you try moving the data into a STL Set ? you need only to implement the comparison function, and you will end up with a perfectly ordered set of data very fast.
为什么不直接使用
map>
(或multimap
)?Why don't you just use a
map<int, unique_ptr<MyData>>
(ormultimap
)?