C ++:打印或将标准库容器打印到控制台

时间:2015-03-02 05:32:53

标签: c++ printing cout c++-standard-library

C ++打印方式或cout C ++标准库容器到控制台的方式是什么?查看其内容?

另外,为什么C ++库实际上没有为您重载<<运算符?背后有历史吗?

3 个答案:

答案 0 :(得分:2)

operator<<重载ostream是可行的方法。这是一种可能性:

template <class container>
std::ostream& operator<<(std::ostream& os, const container& c)
{
    std::copy(c.begin(),
              c.end(),
              std::ostream_iterator<typename container::value_type>(os, " "));
    return os;
}

然后你可以简单地写:

std::cout << SomeContainer << std::endl;

以下是其他一些非常好的解决方案:Pretty-print C++ STL containers

答案 1 :(得分:1)

最简单的方法是使用基于范围的for语句。例如

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

template <class Container>
std::ostream & display( const Container &container, 
                        const char *s = " ",
                        std::ostream &os = std::cout )
{
    for ( const auto &value : container )
    {
        os << value << s;
    }

    return os;
}

int main()
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    std::vector<int> v( std::begin( a ), std::end( a ) );

    display( a, "; " );
    std::cout << std::endl;

    display( v );
    std::cout << std::endl;

    return 0;
}

程序输出

0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 
0 1 2 3 4 5 6 7 8 9 

然而,更灵活的方法是使用标准算法std::copy。在这种情况下,您可以自己设置显示的范围并使用反向迭代器。 此外,您可以编写函数,以获取更多信息。

  

为什么C ++库实际上不会重载&lt;&lt;&lt;&lt;&lt;运营商给你?

因为从我的演示程序的输出中可以看出,任何用户都可以使用他自己的方法输出容器。实际上,容器是用户定义的类,用户应该重载operator&lt;&lt;。 std :: string和std :: bitset有例外,但是字符串和位集作为一个实体输出,没有中间分隔类似于基本类型。

答案 2 :(得分:0)

要想变种,请制作适配器,例如

template< typename T >
struct SequencePrinter
{
    const T& t;
    // ...
};
template< typename T >
SequencePrinter<T> sequence_printer(const T&);
template< typename T >
ostream& operator<<(ostream&, SequencePrinter<T>);
int main() {
    vector<int> v;
    // ...
    cout << sequence_printer(v) << endl;
}

这允许使用通常的<<表示法,但不会强制特定选择<<对序列的含义。当然,它也可以相当可配置。