gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:43:34 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com