假设我有两个如下所示的数组:
first array : 8 5 6 1 4 11 7
second array: 1 1 1 1 0 0 0
我想按降序对第一个数组进行排序,第二个数组中元素的顺序应该按照与第一个数组相同的方式更改,并删除第一个数组中第二个数组中对应值为0的元素。第一个数组中对应值为 0 的元素应该进入另一个数组。最后应打印两个数组的总和。
所以最终的数组应该是这样的:
first array : 8 6 5 1
second array: 1 1 1 1
sum= 8+6+5+1=20
具有值的新数组:
first array : 11 7 4
second array: 0 0 0
sum = 11+7+4=22
关于如何在 C++ 中执行此操作的任何想法
这是我到目前为止所做的...我尝试使用 waytoShort() 方法:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool wayToSort(int a, int b)
{
return a > b;
}
int main()
{
int n;
int sum;
sum=0;
cout<<"no. of elements in first array: "<<endl;
cin>>n;
//no. of elements in both array should be same.
vector<int> l(n);
vector<int> t(n);
for(int i=0;i<n;i++)
{
cin>>l[i]>>t[i];
}
sort(l.begin(),l.end(),wayToSort);
for(int i=0;i<n;i++)
{
cout<<l[i]<<" "<<t[i]<<endl;
}
for(int j= 0; j<n;j++)
{
sum = sum+l[j];
}
cout<<sum<<endl;
return 0;
}
这只会对第一个数组进行排序。
最佳答案
请注意,您可以在对数组进行排序之前将数组拆分为两部分,然后分别对每个数组进行排序。
示例:
8 5 6 1 4 11 7
1 1 1 1 0 0 0
拆分成:
1) [8 5 6 1],[1,1,1,1]
2) [4 11 17],[0,0,0]
然后对每个数组单独排序,结果:
1) [8 6 5 1],[1,1,1,1]
2) [17 11 4],[0,0,0]
关于c++ - 使用c++根据第一个数组中的元素对第二个数组进行排序并删除一些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38145968/