Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Printing or cout a standard library container to console

What's the C++ way to print or cout a C++ standard library container to the console, to view its contents?

On a separate note, why doesn't the C++ library actually overload the << operator for you? Any history behind it?

like image 379
hlin117 Avatar asked Mar 02 '15 05:03

hlin117


People also ask

How to print to console in C/C++?

Write (), and writeLine () are two functions to print to the console. Similarly, ReadLine () is a built-in feature in C # to get value from the console. So this function will be used to get the value from the user. Let us start with the source code description. Inside the main program, declare a string variable.

What are containers in C++ STL (Standard Template Library)?

Containers in C++ STL (Standard Template Library) 1 array: Static contiguous array (class template) 2 vector: Dynamic contiguous array (class template) 3 deque: Double-ended queue (class template) 4 forward_list: Singly-linked list (class template) 5 list : Doubly-linked list (class template) More ...

What is The cout object in C++?

The cout object in C++ is an object of class ostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout.

How to print more than one variable with Cout in C++?

Note: More than one variable can be printed using the insertion operator (<<) with cout. Below is the C++ program to implement the above approach: The cout statement can also be used with some member functions:


1 Answers

Overloading the operator<< for ostream is the way to go. Here's one possibility:

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;
}

Then you can simply write:

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

Here are some other actually really nice solutions: Pretty-print C++ STL containers

like image 138
emlai Avatar answered Sep 29 '22 11:09

emlai