33

有什么方法可以永久设置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.

4

2 回答 2

20

好吧,这是不可能的。没有办法让它.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)
        );
}

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

于 2009-01-01T15:39:05.423 回答
14

由于setw并且width不会导致持久设置,因此一种解决方案是定义一个覆盖 的类型,在值之前operator<<应用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)和宽度(值),以及(2)适用于每个插入operator<<的 anostream和 a 。FixedWidthValsetw

// 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,
于 2014-08-07T01:53:37.190 回答