. Advertisement .
..3..
. Advertisement .
..4..
Hello experts, I’m new to programming, so my understanding is still poor. Please guide me a simple way to print out the contents of a std::vector to the screen in c++. I really appreciate your help. Thanks in advance.
Hi, I’m happy to be able to help you. Hope some of my methods below will be useful to print out the contents of a std::vector to the screen in c++.
Solution 1: Utilizing Indices
The simplest approach is to iterate through the vector’s elements using a basic for-loop and access them using the
[]
operator/at()
function with the appropriate index.Output:
Solution 2: Utilizing the std::copy method
With the aid of the output iterator
std::ostream_iterator
, we can usestd::copy
to copy the contents of the vector to the output streamstd::cout
.Same output as above.
Solution 3: Utilizing Range-based for-loop
For printing elements of a container with C++11, the suggested method is to use a range-based for-loop:
Same output as above.
Solution 4: Utilizing
std::for each
function.It applies a function to each element in a range that is defined by two input iterators. The function may take the form of a lambda expression, an item of one class overloading the
()
operator, or a unary function.The output is the same as above.