33

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::copysetwstd::cout

4

2 に答える 2

20

まあ、それは不可能です。.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)
        );
}

独自のファンクターを作成しますが、舞台裏で発生します:)

于 2009-01-01T15:39:05.423 に答える
14

setwandwidthは永続的な設定にはならないため、1 つの解決策は、値の前に適用して をオーバーライドする型を定義することですoperator<<setwこれにより、ostream_iteratorそのタイプの for が以下のように機能できるようになりstd::copyます。

int fieldWidth = 4;
std::copy(v.begin(), v.end(),
    std::ostream_iterator< FixedWidthVal<int,fieldWidth> >(std::cout, ","));

次のように定義できます: (1)データ型 ( ) と幅 (値) のFixedWidthValパラメーターを持つテンプレート クラスとして、および (2)各挿入に適用されるanおよび a の。typenameoperator<<ostreamFixedWidthValsetw

// 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,
于 2014-08-07T01:53:37.190 に答える