将整数列表打印为逗号分隔的数字列表,每行最多 10 个
Printing a list of integers as comma separated list of numbers with max 10 per line
我有一个数字列表。我想将它们打印为逗号分隔的数字列表,每行最多 10 个数字。下面的程序片段放入逗号分隔的数字列表,不使用显式的 for 循环来迭代整数的向量,我可以每行最多打印 10 个数字吗?
std::vector<int> myvector;
for (int i=1; i<10; ++i) myvector.push_back(i*10);
stringstream ss;
std::copy(myvector.begin(), myvector.end(),
std::ostream_iterator<int>(ss, ", "));
cout << "list: " << ss.str() << endl;
输出显示为(末尾有额外的逗号):
list: 10, 20, 30, 40, 50, 60, 70, 80, 90,
我找到了解决原始问题的方法:
// print at most 6 per line
int maxperline = 6;
std::vector<int>::const_iterator i1,i2,i3;
stringstream ss;
ss << "list: ";
for (i1 = myvector.begin(), i2 = myvector.end(); i1 < i2; i1+=maxperline) {
i3 = min(i2, i1+maxperline);
std::copy(i1, i3-1, std::ostream_iterator<int>(ss, ", "));
ss << *(i3-1) << 'n';
}
cout << 'n' << ss.str() << endl;
输出显示为:
list: 10, 20, 30, 40, 50, 60
70, 80, 90
在这种方法中,我们可以通过将maxperline设置为您想要的值来获得灵活性
对输出项有一些count
,然后使用它。
int count = 0;
for (int i : myvector) {
if (count > 0) std::cout << ", ";
std::cout << i;
if (count % 10 == 0 && count >0) std::cout << std::endl;
count++;
}
如果你真的想使用<algorithm>
你可以有一个匿名的lambda
int count;
std::for_each(myvector.begin(), myvector.end(),
[&](int i) {
if (count > 0)
std::cout << ", ";
std::cout << i;
if (count % 10 == 0 && count >0)
std::cout << std::endl;
count++;
});
(我们显然需要在闭包中通过引用捕获和关闭count
和std::cout
,因此[&]
......
但老实说,在这种特殊情况下,使用上述std::for_each
进行编码是迂腐的。使用像我的第一个示例这样的普通范围for
循环更短、更合适。
顺便说一句,好的优化编译器(可能包括最近作为g++ -Wall -O2 -std=c++11
调用的GCC)可能会将第二个解决方案(使用std::for_each
)优化为等同于第一个解决方案(使用for
,并且不分配闭包)。
您甚至可以尝试以纯粹的延续传递风格对该片段进行编码(在count==0
时和count%10==0
时以不同的延续方式进行编码),但那将是病态的、不可读的,并且编译效率较低......
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 试图在c++中对数字列表进行排序
- 如果我不知道每个列表中有多少个数字,我如何将给定数量的数字列表作为输入?
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 按唯一标识符描述数字列表
- 从小于或等于某个 N 的数字列表中最小化或找到 n 个理想的子集和
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 用于筛子的最佳数据结构是什么(即一些被划掉的数字列表)?
- 最大数量.给定一个非负整数列表,排列它们以使它们形成最大的数字
- 从(排序的)数字列表中获取数字范围
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- 如何在C++中创建数字列表,以便它可以选择一个随机数?
- C - 将数字添加到列表中?(就像python)
- 可以将数字的大括号列表用作传递给可变参数函数(或构造函数)的参数吗?
- 输入正整数或负整数列表,以使用开关函数 c++ 确定数字是偶数还是奇数
- 使用数字列表和算术运算获取目标数字
- 如何通过C 从数字列表中以3位数字生成数字
- 成员初始化列表中初始化的向量与传递给构造函数的数字不同
- 卡在 if 语句中,以检查列表中的数字
- 在 c++ 中将数字从列表排序到数组中的气泡排序问题