×

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector.

A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same type in storage. As a result, it is simpler to access the pieces contained there thanks to their positions.

Vectors are referred to as dynamic arrays because they may dynamically resize themselves when an element is added or removed, with the container taking care of its storage automatically.By including the vector header file as #includevector> at the beginning of the program , these vectors are used in C++ program s.

As a result, an array of vectors is a two-dimensional array with a set number of rows and a variable number of rows per vector. Iterators can be used to traverse and access the vectors that are stored in each index of an array.

Syntax:

vector <data_type>identifier[size];

We can break down the syntax for a vector array into its component pieces because we have already seen that it is vector <data_type>identifier[size].

Example:

Vector <int>A [5];
Where A is the vectors array of int of size 5

Insertion:

The push back() function is used for vector array insertion.

Example:

for I n [0,n) {
          A[i]. push_back (35)
      }

The above pseudo-code inserts element 35 into the vector int> A[n] at every index.

Example:

#include <iostream>
#include <vector>
usingnamespacestd;
int main()
{
    // quantity of vectors
intn;
    court<<"Enter number of vectors in array : ";
cin>>n;
    // creating array of vectors "vec" with size n(vectors)
    vector<int>vec [n];
    // input components are added to each vector
for (inti=0; i<n; i++){
cout<<"Enter number of elements in vector "<<i+1<<" : ";
intnum;
cin>>num;
cout<<"Enter elements into vector "<<i+1<<" : ";
for (int j=0; j<num; j++){
inttemp;      // to pull a component from the input back into a vector
cin>>temp;
vec[i].push_back(temp);
        }
    }
    // printing vector-based elements
cout<<"Method 1 : Using size() method"<<endl;
cout<<"Elements are : "<<endl;
for(inti=0; i<n; i++){
cout<<"Vector "<<i+1<<" : ";
int size = vec[i].size();
for(int j=0; j<size; j++)
cout<<vec[i][j]<<" ";
cout<<endl;
    }
cout<<"Method 2 : Using iterators method"<<endl;
for(inti=0; i<n; i++){
cout<<"Vector "<<i+1<<" : ";
for(auto it = vec[i].begin();it != vec[i].end(); it++)
cout<< *it << ' ';
cout<<endl;
    }
return0;
}

Output:

Array of Vectors in C++ STL

Working

It is quite simple to carry out certain fundamental operations on an array using the STL library, including as sorting, searching, adding up the elements, and determining the array's minimum and maximum elements.

Traversal

Iterators are used to execute vector array traversal.

Example:

For I in [0,n) {
         For (iterator it = A [i]. begin ();
            It! =A[i].end (); it++) {
          Print (*it)
        }
     }

By using the beginning iterator, A[i]. begin() and the ending iterator A[i]. end, the pseudo-code explores the vector int> A[n] at each index (). Since iterators are pointers pointing to elements in vector int> A[n], it uses (*it) to access the element.

The program used to demonstrate the insertion into the vector array is shown below.

Example:

// a C++ application to display
// a vector array
  
#include <iostream>
#include <vector>
usingnamespacestd;
  
// declaring a vector array
// globally
vector<int>v[5];
  
// The ability to introduce elements
// in a vector array
voidinsertionInArrayOfVectors()
{
  
    for (inti = 0; i< 5; i++) {
  
        // Adding components at each
        // using push back in row I ()
        // a vectorized function
        for (int j = i + 1; j < 5; j++) {
            v[i].push_back(j);
        }
    }
}
  
// Function to print elements from a vector array
voidprintElements()
{
  
    // Vectors are traversed to print
    // elements kept there
    for (inti = 0; i< 5; i++) {
  
        cout<< "Elements at index "
             <<i<< ": ";
  
        // each column displaying a different element
        // The initial iterator is begin(),
        // The terminating iterator is end().
        for (auto it = v[i].begin();
             it != v[i].end(); it++) {
  
            // (*it) is used to get the
            // iterator value is
           //indicating
            cout<< *it << ' ';
        }
        cout<<endl;
    }
}
  
// Function that displays an array
// Using vectors
voidarrayOfVectors()
{
    // adding elements to an array
    // using vectors
    insertionInArrayOfVectors();
  
    // Print the array's stored elements.
    // using vectors
    printElements();
}
  
// driver's code
int main()
{
    arrayOfVectors();
    return0;
}
    return0;
}

Output:

Array of Vectors in C++ STL

Related Topics

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

C++ OOPs Concept

The main goal of C ++ programming is to add the idea of ​​object orientation to the C programming language. Inheritance, data binding, polymorphism and other concepts are part of...

4 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.