如何以相同的方式对两个向量进行排序,使用仅使用其中一个向量的条件?
例如,假设我有两个相同大小的向量:
vector<MyObject> vectorA;
vector<int> vectorB;
Run Code Online (Sandbox Code Playgroud)
然后我vectorA
使用一些比较函数排序.排序重新排序vectorA
.如何应用相同的重新排序vectorB
?
一种选择是创建一个结构:
struct ExampleStruct {
MyObject mo;
int i;
};
Run Code Online (Sandbox Code Playgroud)
然后对包含内容vectorA
并将其vectorB
压缩为单个向量的向量进行排序:
// vectorC[i] is vectorA[i] and vectorB[i] combined
vector<ExampleStruct> vectorC;
Run Code Online (Sandbox Code Playgroud)
这似乎不是一个理想的解决方案.还有其他选择,特别是在C++ 11中吗?
我有几个std::vector
,全长相同.我想对这些向量中的一个进行排序,并将相同的变换应用于所有其他向量.这样做有一个简洁的方法吗?(最好使用STL或Boost)?一些向量包含int
s,其中一些包含std::string
s.
伪代码:
std::vector<int> Index = { 3, 1, 2 };
std::vector<std::string> Values = { "Third", "First", "Second" };
Transformation = sort(Index);
Index is now { 1, 2, 3};
... magic happens as Transformation is applied to Values ...
Values are now { "First", "Second", "Third" };
Run Code Online (Sandbox Code Playgroud) 我想获得基于向量的有序索引值(稍后我将使用此索引对另一个向量进行排序)。以下代码适用于我的目的:
std::vector<int> order_ideal(std::vector<double> x) {
std::vector<int> idx(x.size());
std::iota(idx.begin(), idx.end(), 0);
std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] > x[j];});
return idx;
}
Run Code Online (Sandbox Code Playgroud)
但是,无法在 GCC 编译器的早期版本中使用 lambda 函数,因此我正在寻找另一种方法来实现此代码而不使用 lambda 函数。我真的很喜欢如何[&]
捕获外部环境变量。换句话说,我想x
在 std::sort()
.
或者,我可以进行以下工作,但它在我的计算机上比上面的函数慢六倍(我还没有检查它是否与早期的 GCC 版本兼容):
bool isGreater(int i, int j, std::vector<double> x)
{
return x[i] > x[j];
}
std::vector<int> order_bind(std::vector<double> x)
{
std::vector<int> idx(x.size());
std::iota(idx.begin(), idx.end(), 0);
std::sort(idx.begin(), idx.end(), std::bind(isGreater, std::placeholders::_1, std::placeholders::_2, x));
return idx;
}
Run Code Online (Sandbox Code Playgroud)
我有点明白我需要像这里解释的那样将这两个向量(idx
并x
在一起)绑定在一起。但在这种情况下我无法实现它。
我希望按年龄分类
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Person{
std::string name;
int age;
};
struct by_age{
bool operator() (Person const &a,Person const &b){
return a.age>b.age;
}
};
int main(){
vector<Person>people;
for (int i=0;i<4;i++){
cin>>people[i].age>>people[i].name;
}
sort(people.begin(),people.end(),by_age());
for (int i=0;i<4;i++){
cout<<people[i].name<<people[i].age<<" ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码有很多错误请帮忙看看这个网站
我知道这个问题已经 被问 了好 几次,但是对于简单的情况(紧凑性,可读性或用户熟练程度是决定因素)提供了不同的答案,我不确定哪一个是最有效的,因为我担心重复该操作O(1M)次.
设置如下:
A
和B
的float
的; 这不能改变,但可以从A
和创建其他结构B
.A
并且B
长度相等,至少为4,最多为20(如果这对任何方式都有帮助).A
需要根据其条目的值按降序排序,而B
只需要匹配A
的顺序.例:
A = {2,4,3,1} -> {4,3,2,1}
| | | |
B = {1,2,3,4} -> {2,3,1,4}
Run Code Online (Sandbox Code Playgroud)
题:
这样做最有效(快速+节省内存)的方法是什么?