有没有办法永久地设置 std :: setw 操纵器(或其函数 width )?看看这个:

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>

int main( void )
{
  int array[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
  std::cout.fill( '0' );
  std::cout.flags( std::ios::hex );
  std::cout.width( 3 );

  std::copy( &array[0], &array[9], std::ostream_iterator<int>( std::cout, " " ) );

  std::cout << std::endl;

  for( int i = 0; i < 9; i++ )
  {
    std::cout.width( 3 );
    std::cout << array[i] << " ";
  }
  std::cout << std::endl;
}

跑完后,我明白了:

001 2 4 8 10 20 40 80 100

001 002 004 008 010 020 040 080 100

即。除了必须为每个条目设置的 setw / width 之外,每个操纵器都占有一席之地。有没有优雅的方法如何使用 std :: copy (或其他东西)和 setw ?优雅的我当然不是要创建自己的函子或函数来将东西写入 std :: cout

有帮助吗?

解决方案

嗯,这是不可能的。无法再次调用 .width 。但是你当然可以使用boost:

#include <boost/function_output_iterator.hpp>
#include <boost/lambda/lambda.hpp>
#include <algorithm>
#include <iostream>
#include <iomanip>

int main() {
    using namespace boost::lambda;
    int a[] = { 1, 2, 3, 4 };
    std::copy(a, a + 4, 
        boost::make_function_output_iterator( 
              var(std::cout) << std::setw(3) << _1)
        );
}

创建自己的仿函数,但它发生在幕后:)

其他提示

由于 setw width 不会产生持久性设置,因此一种解决方案是定义一个覆盖 operator&lt;&lt; 的类型,在值之前应用 setw 。这将允许该类型的 ostream_iterator std :: copy 一起使用,如下所示。

int fieldWidth = 4;
std::copy(v.begin(), v.end(),
    std::ostream_iterator< FixedWidthVal<int,fieldWidth> >(std::cout, ","));

您可以定义:(1) FixedWidthVal 作为模板类,其中包含数据类型( typename )和width(value)的参数,以及(2)运算符&lt;&lt; 用于 ostream FixedWidthVal ,它为每个插入应用 setw

// FixedWidthVal.hpp
#include <iomanip>

template <typename T, int W>
struct FixedWidthVal
{
    FixedWidthVal(T v_) : v(v_) {}
    T v;
};

template <typename T, int W>
std::ostream& operator<< (std::ostream& ostr, const FixedWidthVal<T,W> &fwv)
{
    return ostr << std::setw(W) << fwv.v;
}

然后它可以用 std :: copy (或 for 循环)来应用:

// fixedWidthTest.cpp
#include <iostream>
#include <algorithm>
#include <iterator>
#include "FixedWidthVal.hpp"

int main () {
    // output array of values
    int array[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };

    std::copy(array,array+sizeof(array)/sizeof(int), 
        std::ostream_iterator< FixedWidthVal<int,4> >(std::cout, ","));

    std::cout << std::endl;

    // output values computed in loop
    std::ostream_iterator<FixedWidthVal<int, 4> > osi(std::cout, ",");
    for (int i=1; i<4097; i*=2)
        osi = i; // * and ++ not necessary

    std::cout << std::endl;

    return 0;
}

输出(演示

   1,   2,   4,   8,  16,  32,  64, 128, 256,
   1,   2,   4,   8,  16,  32,  64, 128, 256, 512,1024,2048,4096,
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top