有什么办法可以设置吗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
IE。每个操纵器都保持其位置,除了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)
);
}
It does创建自己的函子,但它发生在幕后:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)