Vectors


VECTORS

First of all include the header #include<vector> in file;

The capacity of the vector at the time it is initialised is 0,

when value is stored in it, its capacity first increases by 1 and

then gets doubled each time the capacity of the vector lacks.


Vector <datatype> vector_name; //creates vector of size zero.

Vector <datatype> vector_name(n);//creates vector of size n.

vector_name.push_back(any number);//to insert any number in the vector and the value gets inserted in the one by one order.


vector_name.pop_back();  //pops out the last element from the vector.

This function does not reduces the size of the vector once increased by push_back() function.


To enter the elmts in vector with help of loop.

for(i=0; i<n; i++)

{

cin>>a;

vector_name.push_back(a);

}


vector_name.size(); // returns the number of elements filled in vector.

vector_name.capacity(); //returns the capacity of the vector.

vector_name.clear(); // is used to empty the vector.


We can also sort the vector as follows;

vector<datatype>v_name;

sort(v_name.begin(),v_name.end());

ex- In this we have sorted the vector in ascending order and printed

it with help of iterator.

int main() 

    vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; 

    sort(v.begin(), v.end()); 

    cout << "Sorted \n"; 

     vector<int>::iterator ptr; 

     for(ptr=v.begin();ptr<v.end();ptr++)

     cout<<*ptr;

Or

for(int i=0;i<v.size();i++)

cout<<v[i];

     return 0; 

use sort(v.begin(), v.end(),greater<int>())// to sort the vector in

descending order.



To compare two vectors.

#include<bits/stdc++.h>
using namespace std;
// Check if all elements is equal or not
int main()
{
  // Comparing equal vectors
  vector<int> v1{3, 1, 2, 3};
  vector<int> v2{3, 1, 2, 3};
  (v1 == v2)?  cout << "Equal\n" : cout << "Not Equal\n";
    
  // Comparing non-equal vectors
  vector<int> v3{1, 2, 3, 4};
  (v1 == v3)?  cout << "Equal\n" : cout << "Not Equal\n";
    
  // comparing with empty
  vector<int> v4;
  (v1 == v4)?  cout << "Equal\n" : cout << "Not Equal\n";
  
  // comparing two empty
  vector<int> v5;
  (v5 == v4)?  cout << "Equal\n" : cout << "Not Equal\n";
  
   return 0;
}

output:

Equal

Not Equal

Not Equal

Equal

     




Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree