Different Ways To Print Elements Of Vector In C++ - C++ Programming Tutorial
C++ Course / STL Vector / Different Ways To Print Elements Of Vector In C++

Different Ways To Print Elements Of Vector In C++

BLUF: Mastering Different Ways To Print Elements Of Vector In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Different Ways To Print Elements Of Vector In C++

C++ is renowned for its efficiency. Learn how Different Ways To Print Elements Of Vector In C++ enables low-level control and high-performance computing in the tutorial below.

In this guide, you'll explore various methods for displaying vector elements in C++. However, before delving into these techniques, it's essential to understand the fundamentals of vectors, including their benefits and drawbacks.

What are Vectors?

  • Vectors are similar to dynamic arrays in that the container manages their storage.
  • They can automatically resize themselves in response to the insertion or deletion of an element.
  • Vector elements are stored in a contiguous manner , allowing iterators to access and traverse them.
  • Data is inserted at the end of vectors. Inserting at the end requires a variable amount of time because the array may occasionally need to be extended.
  • As no scaling occurs, removing the final element just requires a fixed amount of time. Inserting and erasing at the beginning or in the middle is linear in time.
  • Advantages of the Vectors:

There are several advantages of the vectors . Some main advantages of the vectors are as follows:

  • Dynamic size: You can easily add or remove elements because vectors can resize dynamically. Thus, vectors are preferable to arrays, which have fixed dimensions.
  • Random access: Like an array, elements in a vector can be indexed continuously. Random access functions can now be optimized.
  • Automated memory management: Vector handles memory allocation and allocation automatically. Unlike arrays, you don't have to manually free or allocate memory.
  • Support from the standard library: Because vectors are included in the C++ standard library (<vector> header), they are compatible with many different platforms and compilers
  • Algorithm Compatibility: Vectors are easily handled and manipulated to integrate with standard algorithms provided by standard libraries.
  • Disadvantages of the Vectors:

There are several disadvantages of the vectors . Some main disadvantages of the vectors are as follows:

  • Overhead: Vectors have less overhead than arrays because they hold additional mathematical data (such as size and capacity).
  • Adjacent memory: As vectors store elements in adjacent memory locations, it can be more efficient to insert or remove elements from a vector than it is with linked lists or other data structures
  • Resizing overhead: A vector may need to allocate the old memory, allocate new memory, and move all parts of it to new memory if they need to be expanded beyond what is currently available. Resizing a vector can be expensive when it comes to large vectors.
  • Different ways to Print Elements of a Vector:

There exist numerous techniques for displaying elements of a vector. The primary methods include:

1. Using a for loop:

Program:

Let's consider a program that displays the elements of a vector by utilizing a for loop in the C++ language.

Example

#include <iostream>
#include <vector>
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (size_t i = 0; i < vec.size(); ++i) {
        std::cout << vec[i] << " ";
    }
    return 0;
}

Output:

2. Using Iterators:

Program:

Let's consider a program that displays elements of a vector by utilizing iterators in the C++ language.

Example

#include <iostream>
#include <vector>
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }
    return 0;
}

Output:

3. Using Standard Algorithms with Iterators:

Program:

Let's consider a program that displays the elements of a vector by employing standard algorithms alongside iterators in C++.

Example

#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::for_each(vec.begin(), vec.end(), [](const int& elem) {
        std::cout << elem << " ";
    });
    return 0;
}

Output:

4. Printing elements in reverse order with reverse iterators:

Program:

Let's consider a program that displays the elements of a vector in reverse order utilizing reverse iterators in C++.

Example

#include <iostream>
#include <vector>
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
        std::cout << *it << " ";
    }
    return 0;
}

Output:

5. Using overload (<<) operator:

Program:

Let's consider a program that displays the elements of a vector by overloading the << operator in C++.

Example

#include <iostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
    os << "[";
    for (size_t i = 0; i < vec.size(); ++i) {
        os << vec[i];
        if (i != vec.size() - 1) {
            os << ", ";
        }
    }
    os << "]";
    return os;
}
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::cout << vec << std::endl;
    return 0;
}

Output:

6. Printing elements to the standard output using an ostream_iterator and the copy algorithm:

Program:

Let's consider a program that outputs elements of a vector by utilizing ostream_iterator along with the copy algorithm in C++.

Example

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
    return 0;
}

Output:

7. Working with std:: lambda functionaccumulate to concatenate elements together to form a string, which is then printed:

Program:

Example

#include <iostream>
#include <vector>
#include <numeric>
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::string result = std::accumulate(vec.begin(), vec.end(), std::string{},
                                         [](const std::string& a, int b) {
                                             return a.empty() ? std::to_string(b) : a + " " + std::to_string(b);
                                         });
    std::cout << result;
    return 0;
}

Output:

8. Applying pointer arithmetic and a pointer to the data of the vector:

Program:

Example

#include <iostream>
#include <vector>
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (int* ptr = vec.data(); ptr < vec.data() + vec.size(); ++ptr) {
        std::cout << *ptr << " ";
    }
    return 0;
}

Output:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience