c++ - "Permanent"标准::setw

标签 c++ templates setw

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

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

关于c++ - "Permanent"标准::setw,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/405039/

相关文章:

c++ - codelite unittest++/UnitTest++.h : no such file or directory

c++ - 在元组的每个元素上一般调用成员函数

c++ - 为什么模板只能在头文件中实现?

c++ - mysql C++ 从所有列中选择所有行

c++ - 为什么枚举而不是静态 bool ?

c++ - 堆栈溢出访问大 vector

c++ - 为什么不能为显式模板特化指定默认参数?

c++ - 在数字前面添加 0

c++ - std::stringstream 的默认 `fill character` 是什么?

c++ - iomanip 函数是如何实现的?