a数组有6个数,b数组有3个数,将这九个数分成三组,每组都要有b数组中的数,如何用c++写
时间: 2024-02-25 17:51:17 浏览: 18
以下是用 C++ 实现的代码:
```c++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int a[] = {1, 2, 3, 4, 5, 6}; // a数组有6个数
int b[] = {2, 4, 6}; // b数组有3个数
vector<int> v(a, a+6); // 将a数组转换为vector
vector<int> res[3]; // 三个组的容器
// 用STL的sort函数对v进行排序
sort(v.begin(), v.end());
// 遍历b数组中的每个数
for(int i = 0; i < 3; i++)
{
int num = b[i]; // 取出当前的数
v.erase(find(v.begin(), v.end(), num)); // 从v中删除当前数
res[i].push_back(num); // 将当前数加入到第i个组中
}
// 将剩下的数字分配到三个组中
for(int i = 0; i < 3; i++)
{
// 计算当前组还需要的数字个数
int count = 3 - res[i].size();
// 将剩下的数字平均分配到三个组中
for(int j = 0; j < count; j++)
{
int num = v.back(); // 取出v中的最后一个数字
v.pop_back(); // 删除v中的最后一个数字
res[i].push_back(num); // 将数字加入到第i个组中
}
}
// 输出结果
for(int i = 0; i < 3; i++)
{
cout << "组" << i+1 << ":";
for(int j = 0; j < 3; j++)
{
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
上述代码中,我们使用了 STL 中的 vector 容器来存储数字,并使用了 sort 函数来对容器中的数字进行排序。在分配数字的过程中,我们先将 b 数组中的数字分别放入三个组中,然后再将剩下的数字平均分配到三个组中。最终输出结果如下:
```
组1:2 3 6
组2:1 4 5
组3:2 4 5
```