C++ 基于其他 int 数组排序 [英] C++ Sort based on other int array
问题描述
假设我有两个向量
std::vector<int>vec_int = {4,3,2,1,5};
std::vector<Obj*>vec_obj = {obj1,obj2,obj3,obj4,obj5};
我们如何根据排序的 vec_int 位置对 vec_obj 进行排序?所以目标可能是这样的:
How do we sort vec_obj in regard of sorted vec_int position? So the goal may look like this:
std::vector<int>vec_int = {1,2,3,4,5};
std::vector<Obj*>vec_obj = {obj4,obj3,obj2,obj1,obj5};
我一直在尝试创建新的 vec_array:
I've been trying create new vec_array:
for (int i = 0; i < vec_int.size(); i++) {
new_vec.push_back(vec_obj[vec_int[i]]);
}
但我认为这不是正确的解决方案.我们如何做到这一点?谢谢
But i think it's not the correct solution. How do we do this? thanks
std 库可能是最好的解决方案,但我找不到实现 std::sort 的正确解决方案
std library may be the best solution,but i can't find the correct solution to implement std::sort
推荐答案
你不必调用 std::sort
,你需要的可以在线性时间内完成(前提是索引是从 1 到 N 不重复)
You don't have to call std::sort
, what you need can be done in linear time (provided the indices are from 1 to N and not repeating)
std::vector<Obj*> new_vec(vec_obj.size());
for (size_t i = 0; i < vec_int.size(); ++i) {
new_vec[i] = vec_obj[vec_int[i] - 1];
}
当然,对于这个解决方案,您需要额外的 new_vec
向量.
But of course for this solution you need the additional new_vec
vector.
如果索引是任意的和/或您不想分配另一个向量,则必须使用不同的数据结构:
If the indices are arbitrary and/or you don't want to allocate another vector, you have to use a different data structure:
typedef pair<int, Obj*> Item;
vector<Item> vec = {{4, obj1}, {3, obj2}, {2, obj3}, {1, obj4}, {5, obj5}};
std::sort(vec.begin(), vec.end(), [](const Item& l, const Item& r) -> bool {return l.first < r.first;});
这篇关于C++ 基于其他 int 数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!