Tech Blogs
  • Vivek bhargav
  • Books
    • Seven Databases In Seven Weeks
      • Factors to consider
      • Genres of databases
      • Important questions
      • PostGreSQL
  • Tech
    • C++
      • Type Conversions
      • String
      • Vector
      • Set
      • Unordered Set
      • Map
      • Unordered Map
      • Queue
      • Priority Queue
      • Union find
      • Algorithms
      • Matrix to Graph
      • Trie
      • Dijkstra
      • Math
      • Utils
    • Database Transactions
      • A Simple Transaction Analysis
      • Implementation of Isolation Levels
      • Isolation Levels
      • Isolation
      • Storage Types
      • Transaction Atomicity and Durability
    • Java
      • Important Questions
      • Spring MVC
    • Program execution
      • Node.js
      • Runtimes
    • System Design
      • Basic Terminologies
      • CAP Theorem
      • Normalization of Database
      • Useful Reads
  • Personal Finance
    • Asset Classes
      • Equity instruments
      • Debt instruments
Powered by GitBook
On this page
  1. Tech
  2. C++

Vector


#include <vector>                                  // include vector  in code

vector<int> arr;                                   // create an empty vector
vector<int> arr(10);                               // create a vector of size 10
vector<int> arr{1,2,3};                            // create vector with values 1,2,3
vector<int> arr(10, 5);                            // create an arr of size 10, all elements initialised to 5    

int n = arr.size();                                // get number of elements in arr 

// check if vector is empty  
if (arr.empty()){
    cout << "arr is empty";
}
         
arr.push_back(3);                                  // add element at end of vector 
  
arr.insert(arr.begin(), 7);                        // add an element at beginning of vector

arr.insert(arr.end(), brr.begin(), brr.end());     // add another vector at end of a vector  

arr.clear();                                       // clear all enteries                 

sort(arr.begin(), arr.end());                      // sort vector elements

// sort vector elements in descending order using a comparator function
sort(arr.begin(), arr.end(), [](int lhs, int rhs){
    return (lhs > rhs);     // read it like: lhs should come before rhs if (lhs > rhs)
                            // or read it like: 
                            // In the final sorted array, relation between lhs and rhs is lhs > rhs
});
PreviousStringNextSet

Last updated 1 month ago