题目描述
现在有多组整数数组,需要将它们合并成一个新的数组。
合并规则,从每个数组里按顺序取出固定长度的内容合并到新的数组中,取完的内容会删除掉,如果该行不足固定长度或者已经为空,则直接取出剩余部分的内容放到新的数组中,继续下一行。
输入描述
第一行是每次读取的固定长度,0 < 长度 < 10
第二行是整数数组的数目,0 < 数目 < 1000
第3 − n 行是需要合并的数组,不同的数组用回车换行分隔,数组内部用逗号分隔,最大不超过100个元素。
输出描述
输出一个新的数组,用逗号分隔。
样例1
输入
3
2
2,5,6,7,9,5,7
1,7,4,3,4
输出
2,5,6,1,7,4,7,9,5,3,4,7
说明
1、获得长度3和数组数目2
2、先遍历第一行,获得2,5,6
3、再遍历第二行,获得1,7,4
4、再循环回到第一行,获得7,9,5
5、再遍历第二行,获得3,4
6、再回到第一行,获得7,按顺序拼接成最终结果
样例2
输入
4
3
1,2,3,4,5,6
1,2,3
1,2,3,4
输出 1,2,3,4,1,2,3,1,2,3,4,5,6
C++源码
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main()
{
int readCnt = 0;
std::cin >> readCnt;
int n = 0;
std::cin >> n;
std::cin.ignore();
std::vector<int>cnt(n, 0);
std::vector<std::vector<std::string>>vec;
int total = 0;
for (int i = 0; i < n; i++)
{
std::string line;
std::getline(std::cin, line);
std::stringstream ss(line);
std::string num;
std::vector<std::string>temp;
while (std::getline(ss, num, ','))
{
if (num != "") { // 需要判断
temp.push_back(num);
total++;
}
}
vec.push_back(temp);
}
std::vector<std::string>res;
while (res.size() != total)
{
for (int i = 0; i < vec.size(); i++)
{
int count = 0;
while (count < readCnt && !vec[i].empty())
{
res.push_back(vec[i].front());
vec[i].erase(vec[i].begin());
++count;
}
if (vec[i].empty()) {
vec.erase(vec.begin() + i);
i--;
}
}
}
for (int i = 0; i < res.size(); i++) {
if (i != 0) std::cout << ',';
std::cout << res[i];
}
return 0;
}