我有一个向量元素std::vector<T> my_vec
。在代码的某个点上,我使用无序映射为向量的每个元素分配一个分数。之后,我想用可能的最少代码按向量元素的分数对向量进行排序。
我想出了这个解决方案,定义图如下:std::unordered_map<const T*, float> scores_map
。对于分数分配,将分数插入地图,如下所示:
for (const auto& el : my_vec)
scores_map[&el] = calc_score(el);
然后我使用:
std::sort(my_vec.begin(), my_vec.end(),
[&my_map](const auto& a, const auto& b){return my_map[&a] > my_map[&b];});
如果不知道如何做到这一点,这是否被认为是没有错误并且是好的做法?
@fas在评论中写道:
向量中的元素在排序过程中会移动,因此它们的指针也会更改并
scores_map
变为无效,不是吗?
那是对的。您不应该将指针用作中的键scores_map
。
如果向量包含唯一项,则可以将T
用作键类型。
for (const auto& el : my_vec)
scores_map[el] = calc_score(el);
然后使用:
std::sort(my_vec.begin(), my_vec.end(),
[&my_map](const auto& a, const auto& b){return my_map[a] > my_map[b];});
如果向量不包含唯一元素,则可以使用以下策略。
my_map
。std::vector<size_t>
仅包含索引的帮助程序对象。my_vec
。for (size_t i = 0; i < my_vec.size(); ++i )
scores_map[i] = calc_score(my_vec[i]);
// Create the vector of indices
std::vector<size_t> indices_vec(my_vec.size());
for ( size_t i = 0; i < indices_vec.size(); ++i )
{
indices_vec[i] = i;
}
// Sort the vector of indices
std::sort(indices_vec.begin(), indices_vec.end(),
[&my_map](size_t a, size_t b){return my_map[a] > my_map[b];});
for (auto index : indices_vec)
{
// Use my_vec[index]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句