問題描述
有沒有辦法永久設置 std::setw
操縱器(或其功能 width
)?看看這個:
Is there any way how to set std::setw
manipulator (or its function width
) permanently? Look at this:
#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
.
I.e. every manipulator holds its place except the setw
/width
which must be set for every entry. Is there any elegant way how to use std::copy
(or something else) along with setw
? And by elegant I certainly don't mean creating own functor or function for writing stuff into std::cout
.
推薦答案
好吧,這是不可能的.沒有辦法讓它每次都調用 .width
.但是你當然可以使用 boost:
Well, it's not possible. No way to make it call .width
each time again. But you can use boost, of course:
#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 create its own functor, but it happens behind the scene :)
這篇關于“永久"標準::設置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!