std::setw 用于用户定义类型的整个 operator<<

std::setw for the whole operator<< of user-defined type

我们知道,std::setw() 只影响下一个输出。

那么,标准做法要对齐什么 whole operator<< of user-defined type in table output:

class A
{
    int i, j;
public:
    friend ostream& opeartor<<(ostream& out, const A& a) { 
          return << "Data: [" << i << ", " << j << "]";
    }
}

// ...
A[] as;
out << std::left;
for (unsigned i = 0; i < n; ++i)
     out << std::setw(4)  << i
         << std::setw(20) << as[i]  // !!!
         << std::setw(20) << some_strings[i]
         << some_other_classes[i] << std::endl;
out << std::right;

只需将 setw() 方法添加到您的 class:

class A
{
    int i, j;
    mutable int width = -1;

public:
    A& setw(int n) {
        this->width = n;
        return *this;
    }

    friend ostream& operator<<(ostream& out, const A& a);
};

当你打印它时,如果你想对齐,只需使用它:

int main() {
    A as[5];
    for (auto & a : as)
        cout << a.setw(15) << endl;
}