Basics of Vectors in C++

BASIC SYNTAX IN C++


This blog contains the code to the basic syntaxes of vectors & STL in C++.

The first code (copy-paste & execute for yourself) deals with accepting integer type
input and adding it to the vector. Usually vectors work almost exactly like arrays.

Syntax used below -
    vector<int>
    push_back()
    size()

#include<bits/stdc++.h>
using namespace std;
int main()
{
    //declaring the vector of type integer
    vector<int> sample;
    
    //base condition to accept values
    cout<<"Enter the elements"<<endl;
    
    // we check if entered value is integer 
    // type or not
    int n;
    while(cin>>n)
    {
        
        //push_back adds this value to the vector
        sample.push_back(n);
        
    }
    cout<<endl;
    
    cout<<"The elements you entered were-"<<endl;
    //accessing each element of the vector
    for(int i=0;i<sample.size();i++)
    {
        
        //same as normal array
        cout<<sample[i]<<" ";
        
    }
    cout<<endl;
}

The second code (copy-paste & execute for yourself) deals with accepting integer type
input and adding it to the vector. Then we manipulate the vector to print the values
in the vector in ascending order. It is a one line work.

Syntax used below -
    vector<int>
    push_back()
    size()
    sort()
    begin()
    end()

#include<bits/stdc++.h>
using namespace std;
int main()
{
    //just accepting vector values
    vector<int> sample;
    cout<<"Enter the elements<<endl;
    int n;
    while(cin>>n)
    {
        sample.push_back(n);
    }
    cout<<endl;
    
    //how to sort in ascending order?
    sort(sample.begin(),sample.end());
    
    for(int i=0;i<sample.size();i++)
    {
        cout<<sample[i]<<" ";
    }
    cout<<endl;
}

The third code (copy-paste & execute for yourself) deals with accepting integer type
input and adding it to the vector. Then we manipulate the vector to print the values
in the vector in descending order using the 'reverse()' in STL. It is a two line work.

Syntax used below -
    vector<int>
    push_back()
    size()
    sort()
    begin()
    end()
    reverse()

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> sample;
    cout<<"Enter the elements"<<endl;
    int n;
    while(cin>>n)
    {
        sample.push_back(n);
    }
    cout<<endl;
    
    //descending order is the reverse of ascending, 
    //so....
    sort(sample.begin(),sample.end());
    reverse(sample.begin(),sample.end());
    
    for(int i=0;i<sample.size();i++)
    {
        cout<<sample[i]<<" ";
    }
}

Hope this helps you to get started in using vectors C++.

Comments