9

Vector用 C++ 创建了一个类,它对我的​​问题很有用。我现在正在清理它,我遇到了以下代码:

std::ostream& operator<<(std::ostream &output, const Vector &v){
  output<<"["
    <<std::setiosflags(std::ios::right | std::ios::scientific)
    <<std::setw(23)
    <<std::setprecision(16)
    <<v._x<<", "
    <<std::setiosflags(std::ios::right | std::ios::scientific)
    <<std::setw(23)
    <<std::setprecision(16)
    <<v._y<<", "
    <<std::setiosflags(std::ios::right | std::ios::scientific)
    <<std::setw(23)
    <<std::setprecision(16)
    <<v._z<<"]";
  return output;
} 

该代码允许将向量打印为std::cout<<v<<std::endl;. 每个数字有 23 个空格,其中 16 个是小数。文本右对齐,以便打印:

 1.123456123456e+01
-1.123456123456e+01

代替

1.123456123456e+01
-1.123456123456e+01

代码似乎非常重复。您如何“存储”格式(所有setiosflags,setwsetprecision语句),以便您可以说“以标准方式打印字符,但以这种给定格式打印数字”。

谢谢!

编辑

根据 Rob Adams 的评论,我将丑陋的代码(正如其他人所指出的那样,会弄乱“下一个人”的精确度)更简洁(并且正确):

std::ostream& operator<<(std::ostream &output, const Vector &v){
  std::ios_base::fmtflags f = output.flags(std::ios::right | std::ios::scientific);
  std::streamsize p = output.precision(16);
  output<<"["
    <<std::setw(23)<<v._x<<", "
    <<std::setw(23)<<v._y<<", "
    <<std::setw(23)<<v._z
    <<"]";
  output.flags(f);
  output.precision(p);
  return output;
}
4

4 回答 4

11

只是std::setw()暂时的。另外两个调用 ,setiosflagssetprecision具有永久效果。

因此,您可以将代码更改为:

std::ostream& operator<<(std::ostream &output, const Vector &v){
  output<<"["
    <<std::setiosflags(std::ios::right | std::ios::scientific)
    <<std::setw(23)
    <<std::setprecision(16)
    <<v._x<<", "
    <<std::setw(23)
    <<v._y<<", "
    <<std::setw(23)
    <<v._z<<"]";
  return output;
} 

但是现在你已经为下一个人破坏了旗帜和精确度。试试这个:

std::ostream& operator<<(std::ostream &output, const Vector &v){
  std::ios_base::fmtflags f = output.flags(std::ios::right | std::ios::scientific);
  std::streamsize p = output.precision(16);
  output<<"["
    <<std::setw(23)
    <<v._x<<", "
    <<std::setw(23)
    <<v._y<<", "
    <<std::setw(23)
    <<v._z<<"]";
  output.flags(f);
  output.precision(p);
  return output;
} 

最后,如果你绝对必须摆脱常量的重复23,你可以做这样的事情(但我不推荐它):

struct width {
  int w;
  width(int w) : w(w) {}
  friend std::ostream& operator<<(std::ostream&os, const width& w) {
    return os << std::setw(width.w);
  }
};


std::ostream& operator<<(std::ostream &output, const Vector &v){
  std::ios_base::fmtflags f = output.flags(std::ios::right | std::ios::scientific);
  std::streamsize p = output.precision(16);
  width w(23);
  output<<"["
    <<w
    <<v._x<<", "
    <<w
    <<v._y<<", "
    <<w
    <<v._z<<"]";
  output.flags(f);
  output.precision(p);
  return output;
} 

另请参阅this other question,他们决定您不能永久设置宽度。

于 2011-03-16T17:03:25.270 回答
3

在 C++20 中,您将能够:

std::ostream& operator<<(std::ostream& output, const Vector& v){
  const int width = 23, precision = 16;
  return output << std::format(
      "[{0:{3}.{4}e}, {1:{3}.{4}e}, {2:{3}.{4}e}]",
      v._x, v._y, v._z, width, precision);
} 

与 I/O 操纵器不同,std::format不会更改ostream的格式化状态,从而避免 Bo Persson 提到的问题:

你真正的问题是这个之后的下一个输出会发生什么......

它也可以使 I/O 操纵器与Vector.

std::format可用之前,您可以使用它所基于的 {fmt} 库。

于 2021-03-03T04:58:37.257 回答
2

除了 setw() 之外的所有东西实际上已经这样做了。它们是“粘性的”。

你真正的问题是这个之后的下一个输出会发生什么......

于 2011-03-16T16:57:17.047 回答
2

通常,您不直接使用标准操纵器。例如,在这种情况下,您可以从向量定义一个操纵器,并使用它:

output << '['
       << fromVector << v.x << ", "
       << fromVector << v.y << ", "
       << fromVector << v.z << ']';

这样,如果你想改变向量中元素的宽度和精度,你只需要在一个地方做。

在这种情况下,操纵器没有参数,只需要一个简单的函数:

std::ostream& fromVector(std::ostream& stream)
{
    stream.setf(std::ios::right, std::ios::adjustfield);
    stream.setf(std::ios::scientific, std::ios::floatfield);
    stream.precision(16);
    stream.width(32);
    return stream;
}

当然,这将改变任何以后用户的大部分格式。一般来说,最好使用临时类对象来保存状态,并在析构函数中恢复它。我通常从以下方面派生我的操纵器:

标头:类StateSavingManip {公共:StateSavingManip(StateSavingManip const&其他);

    virtual             ~StateSavingManip() ;
    void                operator()( std::ios& stream ) const ;

protected:
                        StateSavingManip() ;

private:
    virtual void        setState( std::ios& stream ) const = 0 ;

private:
    StateSavingManip&   operator=( StateSavingManip const& ) ;

private:
    mutable std::ios*   myStream ;
    mutable std::ios::fmtflags
                        mySavedFlags ;
    mutable int         mySavedPrec ;
    mutable char        mySavedFill ;
} ;

inline std::ostream&
operator<<(
    std::ostream&       out,
    StateSavingManip const&
                        manip )
{
    manip( out ) ;
    return out ;
}

inline std::istream&
operator>>(
    std::istream&       in,
    StateSavingManip const&
                        manip )
{
    manip( in ) ;
    return in ;
}

来源: int getXAlloc() ;int ourXAlloc = getXAlloc() + 1 ;

int
getXAlloc()
{
    if ( ourXAlloc == 0 ) {
        ourXAlloc = std::ios::xalloc() + 1 ;
        assert( ourXAlloc != 0 ) ;
    }
    return ourXAlloc - 1 ;
}
}

StateSavingManip::StateSavingManip()
    :   myStream( NULL )
{
}

StateSavingManip::StateSavingManip(
    StateSavingManip const&
                        other )
{
    assert( other.myStream == NULL ) ;
}

StateSavingManip::~StateSavingManip()
{
    if ( myStream != NULL ) {
        myStream->flags( mySavedFlags ) ;
        myStream->precision( mySavedPrec ) ;
        myStream->fill( mySavedFill ) ;
        myStream->pword( getXAlloc() ) = NULL ;
    }
}

void
StateSavingManip::operator()( 
    std::ios&           stream ) const
{
    void*&              backptr = stream.pword( getXAlloc() ) ;
    if ( backptr == NULL ) {
        backptr      = const_cast< StateSavingManip* >( this ) ;
        myStream     = &stream ;
        mySavedFlags = stream.flags() ;
        mySavedPrec  = stream.precision() ;
        mySavedFill  = stream.fill() ;
    }
    setState( stream ) ;
}

如果这样做,则必须在操纵器后添加括号,例如:

output << '['
       << fromVector() << v.x << ", "
       << fromVector() << v.y << ", "
       << fromVector() << v.z << ']';

(我相信一些聪明的灵魂会想办法避开它们,但它们从来没有打扰过我,所以我没有打扰过。)

于 2011-03-16T17:40:14.403 回答