Print Vector in C++

Print Vector C++

This article discusses the vector and how to print vector in C++.

Vectors are similar to dynamic arrays in that they can resize themselves automatically when an element is added or removed. The container automatically handles the size of the vector.

Elements in a vector are stored in contiguous memory locations. You can traverse these elements using indices or by iterators.

Print Vector in C++ Using Indices

You can access the elements of a vector using indices within the square brackets ([]).

To print the vector,

  • Start traversing the vector from the first element using a loop. Start at 0-index.
  • Print the current element.

Let us see the code that uses for-loop to print the vector using indices.

Notice the size() function in the loop. It returns the number of elements in the vector.

Output:

10 20 30 40 50 60

Print Vector in C++ Using Range-Based for Loop

C++11 added the range-based for loop. It is more compact than the traditional for loop in the sense that you do not have to manually specify starting and ending iterators or indices.

The range-based for loop automatically traverses all the elements of the vector.

Let us see the code.

Output:

1 2 3 4 5 6

Print Vector in C++ Using for_each() Function

The for_each() function facilitates the tasks where you need to apply a function to all the elements within a range of a container such as a vector.

You can print the elements of the vector by calling the for_each() and passing the starting and ending iterators to it as arguments.

Note that you must also create a function that takes an element of your vector’s data type and print it. This function is passed to the for_each() function as the third argument.

The definition of the for_each() is given below.

Let us see the code.

Output:

3 1 5 7 2 9

Print Vector in C++ Using Iterator

Iterators are similar to pointers and point to a specific memory location of the vector. You can use the following methods to retrieve iterators and use them to traverse the vector.

  1. begin(): Returns an iterator pointing to the vector’s first element.
  2. end(): Returns an iterator pointing to the theoretical element following the vector’s last element.

Let us see the code.

Output:

1 1 1 7 2 9

You can note the use of the auto keyword. To know more about this keyword, you can visit here.

Print Vector in C++ by Overloading the Insertion Operator (<<)

The insertion operator (<<) in C++ is used to direct the objects to a stream. Generally, you might have used it to print the data to the console output.

However, C++ provides a facility to overload the insertion operator (<<). Therefore, you can make use of this functionality to print the elements of the vector.

You would need to overload the insertion operator (<<) by defining your own ostream class operator (<<) to print the vector.

You can overload the ostream operator to accept the arguments as given below.

Let us see the code.

Output:

1 2 5 7 2 9

Print Vector in C++ Using copy() Function

The copy() function is C++ copies all the data elements of a container within a range to an output iterator.

You can create an output iterator to the console output using the ostream_iterator() function. To do so you need to pass the cout and the separator (“ ”) to the function.

Finally, you can pass the starting iterator and ending iterator of vector and output iterator to the copy() function. It prints all the elements of the vector.

The definition of the copy() is given below.

Let us see the code.

Output:

1 2 2 2 2 9

Conclusion

You have seen several different methods to print the vector elements in C++. All of these methods apply best to different situations. However, using copy() lets you avoid the loop.

On the other hand, if you need to print the vector too frequently, it would be better to overload the insertion operator (<<). Or you also define a function that prints the vector using any of the methods given in the article.

This is all about how to print vector in C++.

Hope you have enjoyed the article. Stay tuned for more such articles. Happy Learning!

References

  1. https://www.cplusplus.com/reference/algorithm/copy/
  2. https://www.cplusplus.com/reference/algorithm/for_each/
  3. https://www.cplusplus.com/reference/iterator/ostream_iterator/

Was this post helpful?

Related Posts

  • 19 May

    Get Type of Object in C++

    Table of ContentsWhy Should We Determine the Type of Object in C++: Dynamic DispatchingGet Type of Object in C++ConclusionWas this post helpful? C++ is an object-oriented language where we often interact with objects of different types. The object interaction becomes more interesting when we add runtime polymorphism to it. The runtime polymorphism, also known as, […]

  • 19 May

    Convert Vector to Array in C++

    Table of ContentsVectors and Arrays in C++Convert Vector to Arrays in C++Using the for loop to convert vector to array in C++Using the copy() function to convert vector to array in C++Using the transform() function to convert vector to array in C++Using the data() function to convert vector to array in C++Using the & operator […]

  • How to initialize an array in Constructor in C++
    23 April

    How to initialize an Array in Constructor in C++

    Table of ContentsArraysConstructors of a ClassWays to initialize an array in Constructor in C++Initialize an array in Constructor With std::fill()Initialize an array in Constructor Using for LoopInitialize an array in Constructor Using Member Initializer ListConclusionWas this post helpful? This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays […]

  • Write String to file in C++
    31 March

    Write String to File in C++

    Table of ContentsUsing the fstream Library to write String to File in C++Using the Insertion Operator (<<) With the fstream ObjectUsing the write() Function of the fstream LibraryUsing the fwrite() Function to write String to File in C++ConclusionWas this post helpful? The files are used to store the data permanently on a disk. This mitigates […]

  • Print Array in C++
    23 March

    Print Array in C++

    Table of ContentsIntroduction of ArraysDifferent Methods to Print an Array in C++print array in C++ by Traversing Indicesprint array in C++ Using for_each() Functionprint array in C++ Using Range-Based for Loopprint array in C++ Using Iteratorsprint array Using ostream_iterator() Function and copy() Functionprint array Using C++17 copy() Function and make_ostream_joiner() FunctionConclusionWas this post helpful? An […]

  • Print Map in C++
    15 March

    Print Map in C++

    Table of ContentsMap vs Unordered MapPrint Map in C++ Using IteratorPrint Map in C++ Using Range-Based for LoopPrint Map in C++ by Overloading the ostream Insertion Operator (<<)Print Map in C++17 Using Structure Binding and Range-Based for LoopPrint Map in C++17 Using for_each() FunctionConclusionReferencesWas this post helpful? Maps in C++ store the data in form […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.