使用c++根据第一个数组中的元素对第二个数组进行排序,并删除一些元素
Sort second Array according to the elements in the first array using c++ and remove some elements
假设我有两个这样的数组:
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可能会更好。
您正在执行的操作表明您的容器类型是错误的。
- 你是基于"第一个数组"的值排序"第二个数组",保持数组排序将是可取的
- 你正在根据"第二个数组"的值分割数组,如果它们之间有一个链接就好了
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>
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int