将整数列表打印为逗号分隔的数字列表,每行最多 10 个

Printing a list of integers as comma separated list of numbers with max 10 per line

本文关键字:列表 数字 打印 整数 分隔      更新时间:2023-10-16

我有一个数字列表。我想将它们打印为逗号分隔的数字列表,每行最多 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++;
              });

(我们显然需要在闭包中通过引用捕获和关闭countstd::cout,因此[&]......

但老实说,在这种特殊情况下,使用上述std::for_each进行编码是迂腐的。使用像我的第一个示例这样的普通范围for循环更短、更合适。

顺便说一句,好的优化编译器(可能包括最近作为g++ -Wall -O2 -std=c++11调用的GCC)可能会将第二个解决方案(使用std::for_each)优化为等同于第一个解决方案(使用for并且不分配闭包)。

您甚至可以尝试以纯粹的延续传递风格对该片段进行编码(在count==0时和count%10==0时以不同的延续方式进行编码),但那将是病态的、不可读的,并且编译效率较低......

相关文章: