c++ - 使用c++根据第一个数组中的元素对第二个数组进行排序并删除一些元素

标签 c++ arrays sorting

假设我有两个如下所示的数组:

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/

相关文章:

c++ - 如何判断翻译单元是否正在使用分段堆栈进行编译

java - 这是否正确地将名称和等级存储到数组中?

c# - 最快的方法从部分位中获取整数

php - 迭代某个字段排序的 Doctrine Collection

c++ - 数组指针永远不会出现段错误?

c++ - std::vector<double> 的有效子集

python - 数组中一个点与其余点之间的距离

java - 禁用 JTable 上的列标题排序

python - 用 numpy 进行矢量化基数排序——它能打败 np.sort 吗?

C++ 即时启用/禁用 std::couts 的调试消息