“永続的” std :: 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
を呼び出すようにする方法はありません。もちろん、ブーストを使用することもできます:
#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)
);
}
独自のファンクタを作成する が、舞台裏で発生する:)
他のヒント
setw
と width
は永続的な設定にならないため、1つの解決策は operator&lt;&lt;
をオーバーライドする型を定義することです。値の前に 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&lt;&lt;
は ostream
で、 FixedWidthVal
は setw
各挿入に適用されます。
// 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,
所属していません StackOverflow