Vectors in C++-Part -I

A.What are vectors?

Sequence containers known as vectors are categorised as class templates. They are employed to store data in a linear manner. A vector can hold objects of a single data type. With contrast to arrays, we can access elements more quickly in vectors. However, insertion and deletion at any other location besides the end is considerably slower. Additionally, adding any piece at the end goes more quickly.

B. Implementing vectors in our programmes

The header file vector> must be present for our code to be able to use vectors. And a vector is defined using the syntax

vector<data_type> vector_name;

Any data type could be used in place of data type. One advantage of utilising vectors is that unlike arrays, which require a size parameter, vectors allow us to insert as many elements as we like.

The push back method is the first of several ways provided by vectors to access and use their constituent parts. Visit this website, std::vector – C++ Reference, to access all the methods and member functions in detail.

C. Initializing a vector

There are various ways to initialise a vector:

A vector could be initialised using the first technique by having all of its items entered at the time the vector is defined.

vector<int> v = {1, 2, 3, 4};

Another way to initialise a vector is to pass it’s definition along with two parameters, the first of which specifies the vector’s size and the second of which specifies the uniform value the vector will have throughout all of its locations.

vector<int> v(4, 10);

Here, v is of size 4 with value 10 at all positions.

D. Adding components to a vector

A vector can have elements added to it in a variety of ways. When we use the push back method, the most cost-effective way to insert an element into a vector is at the tail. The elements that are to be inserted are passed as an argument to the push back() function, which pushes the element to the back.

#include <iostream>
#include <vector>
using namespace std;
 
void display(vector<int> v)
{
    cout << "The elements are: ";
    for (auto it : v)
    {
        cout << it << " ";
    }
    cout << endl;
}
 
int main()
{
    vector<int> v = {1, 2, 3, 4};
    display(v);
    v.push_back(5); //5 is inserted at the back
    display(v);
}

Output:

The elements are: 1 2 3 4 
The elements are: 1 2 3 4 5
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in