CodeISM Class 3-b (STL Vectors)
CodeISM Class 3-b (STL Vectors)
int arr[100];
// an array of size 100
.size()
Time complexity of O(1)
cout<<vec.size();
0-based indexing
…..
vec[n-1] => nth element of vector
.push_back()
Pushes a value at the back of vector and increases size of
vector by 1
Syntax:
vec.push_back(value);
Time complexity:
O(1)
Eg. 1 A code using push_back():
#include <bits/stdc++.h>
using namespace std;
int32_t main()
{
vector<int> vec(3, 8);
vec.push_back(22);
int n=vec.size();
for(int i=0; i<n; i++)
{
cout<<vec[i]<<" ";
}
return 0;
}
.resize()
Resize the vector to a different size
Eg.
vec.resize(100);
// Make the size of vector 100
.sort()
// Used to arrange all elements of vector in increasing or
ascending order
// O(N log N)
sort(vec.begin(), vec.end());
.reverse()
// Used to reverse a vector
// O(N)
reverse(vec.begin(), vec.end());
Q. Suppose, the input format is given like this:
All elements are given as space separated integers and
last element is -1. Write program to take input of these
integers.
int num=100;
vector<int> vec;
while(num != -1)
{
cin>>num;
vec.push_back(num);
}
Note: But using this syntax, you can can’t change any
value of the original array. (Similar to call by value)
If you want to change all the elements of the array, use
reference variable by putting & sign before variable
name in loop (Similar to call by reference)
Example
for(auto &num: vec)
{
num=100;
}