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?
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.
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 ...
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With