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

Sort second Array according to the elements in the first array using c++ and remove some elements

本文关键字:数组 元素 排序 删除 c++ 第一个 使用 第二个      更新时间:2023-10-16

假设我有两个这样的数组:

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

new array with value:

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]  

如果我理解正确的话,您希望根据第二个元素筛选元组列表,然后希望根据第一个元素对元组列表进行排序。我没有发现对操作顺序有任何重要影响,所以您应该先过滤。

将问题表示为两个不同的元素集合可能不是正确的方法(当然,这假定由于某些外部约束而不需要使用两个单独的列表)。

与上面的保持一致,您应该使用一个列表,但它应该是对的(std::pair)。基于X的任何突变都将隐式地拖拽Y。

对于删除右元素== 0的pair。这应该是线性的。即使您先这样做,也不会注意到对整个运行时的最终影响(对数组的单次运行,因为排序是真正繁重的工作发生的地方)。

对排序相当简单:

对std::vector>用绳子?

数据表示的选择很重要。您可能希望使用std::vector,但由于您可能要删除很多东西,因此性能可能会受到影响。对于大范围的数据集,这可能会引发大规模的重新洗牌。在这些情况下,使用std::list可能会更好。

您正在执行的操作表明您的容器类型是错误的。

  1. 你是基于"第一个数组"的值排序"第二个数组",保持数组排序将是可取的
  2. 你正在根据"第二个数组"的值分割数组,如果它们之间有一个链接就好了

multimap已经完成了1,所以你永远不需要排序你的键("第一个数组")。给定multimap<int, int> arrays 2可以这样做:

 multimap<int, int> newarrays;
 auto it = begin(arrays);
 while(it != end(arrays)) {
    if(it->second != 0) {
        ++it;
    } else {
        newArrays.insert(*it);
        it = arrays.erase(it);
    }
}
<

生活例子/kbd>