【问题标题】:Printing a list of integers as comma separated list of numbers with max 10 per line [duplicate]将整数列表打印为逗号分隔的数字列表,每行最多 10 个 [重复]
【发布时间】:2016-01-20 08:31:02
【问题描述】:

我有一个数字列表。我想将它们打印为逗号分隔的数字列表,每行最多 10 个数字。下面的程序 sn-p 放入逗号分隔的数字列表,没有使用显式的 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 设置为您想要的值来获得灵活性

【问题讨论】:

  • 未来的范围算法可能会有所帮助。特别是view::chunk.

标签: c++ vector stl ostream


【解决方案1】:

有一些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++;
}

如果你真的想使用&lt;algorithm&gt;,你可以有一个匿名 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 在闭包中被捕获和关闭通过引用,因此 [&amp;]....)

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

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

您甚至可以尝试在纯continuation-passing style 中编码该片段(count==0count%10==0 等时使用不同的延续)但这会很糟糕,不可读,并且编译效率较低......

【讨论】:

  • 这会起作用,但我正在寻找使用 std::copy 或类似方法而不使用 for 循环的解决方案
  • 我编辑了我的 Q 以添加我自己的答案
猜你喜欢
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多