Array and Vector
Array and Vector
Arrays can be described as a type of data structure used to store a group or collection of items or elements
The main function of an Array is to store a collection of homogenous data of the same type. For example,
The indexing of an Array is 0 based indexing ie the first element is at index 0 and the second element is at
index 1 and so forth. We can directly access the required elements using the indexes
Some examples:
Array Literal
With curly braces we can initialize the array and add value to it during initialization without defining the size
4,5,6,7,8,9,10 };
Array Types
Multidimensional Arra
When we have elements stored in a single dimension sequentially, they are called single dimensional arrays
We can declare and allocate memory to a single-dimensional array using a single variable in C++.
Here is an example,
Since we have come this far in arrays, it is worth mentioning here that there is a provision in C++ wherein we
can store the elements/data dynamically and sequentially. That means the length of this container is dynamic.
Java
C++ &+ DSA
DSA
Vectors in C++
Vectors are dynamic arrays that can be resized whenever an element is inserted or deleted. Vectors also have
contiguous storage like arrays but their size can change dynamically according to the requirements of user.
Another important point to note here is that vectors are not compulsorily bound by index values.
Example: vector<int>myVec;
Note: We can even declare a vector of fixed size also with the following syntax:
vector<int> v(n);
Example:
vector<int>v = {10,20,30,40,50};
O utput : 5
Unlike the fixed size approach of arrays, we can resize the vector according to our requirement.
Example:
vector<int> v;
v.resize(n);
Note: This is extremely useful when we do not know the size initially (at the time of creating the vector). It can be
resized anytime as per need.
Vector capacity () function: It returns the size of the storage space allocated to the vector. This capacity is
greater than or equal to the size of the vector catering the need for extra space to allow growth without the
Note: This capacity is not the limit for growth and can be automatically expanded.
Co de Example:
vector<int> v;
v.resize( 10);
v.resize( 90);
Java
C++ &+ DSA
DSA
Output:
16
128
N ote: Whenever we resize and increase the size of the vector, the total capacity gets to the next power of 2 or
the remaining memory. For example, in the above case, the vector size is 10 but its capacity is the closest next
power of 2 i.e.16. When increased to 90, its capacity went to the closest next power of 2 i.e. 128.
Code:
vector<int> v = {10,20,30,40};
v.push_back(50);
Code:
vector<int> v = {10,20,30,40,50};
v.pop_back();
Insert an element somewhere in the vector's middle/ (in between the elements):
Syntax:
vector<int> v;
v.insert(position, value);
Position specifies to the iterator which points to the position where the insertion is to be done.
Example Code:
vector<int> v = {10,20,30,40,50};
v.insert(v.begin() + 2, 100);
{10,20,100,30,40,50}
Syntax:
v.erase(position);
Example Code:
vector<int> v = {10,20,30,40,50};
v.erase(v.begin() + 2);
{10,20,40,50}
Java
C++ &+ DSA
DSA
Clearing the vector : clear() function is used to remove all the elements of the vector container, thus making its
size 0.
Code:
vector<int> v = {10,20,30,40,50};
v.clear();
Output:
Looping in Vector
There are many ways to traverse through the elements of a vector. The most common and widely used ways of
looping are:
For Loop:
#include<iostream>
int main(){
vector<int> v;
v.push_back(i);
Output : 0 1 2 3 4
For each loop: This loop helps in iterating over iterable objects like string, array and so on.
vector<int> a = { 1, 2, 3, 4, 5, 6, 7, 8 };
for (int i : a) {
Output :
Java
C++ &+ DSA
DSA
Explanation : Here, all the elements present in the array will be printed.
While loop:
int main(){
int i = 5;
vector<int> v;
while(i > 0) {
v.push_back(i--);
i = 0;
cout<<v[i]<<" ";
I++;
Output : 5 4 3 2 1
Explanation: Here, we initialize the value of ‘i’ to be 5 and keep decrementing it using the post-
decrement operator and at each step insert it at the back of the vector. Therefore, in the end, the vector will
contain elements from 5 to 0.
Q1. Given an array of marks of students, if the mark of any student is less than 35 print its roll number. [roll
number here refers to the index of the array.]
#include <iostream>
#include <vector>
int main() {
std::vector<int> studentMarks;
int numStudents;
Java
C++ &+ DSA
DSA
std::cout << "Enter the marks of students:" << std::endl;
int mark;
std::cout << "Enter the mark for student " << i << ": ";
studentMarks.push_back(mark);
printFailingStudents(studentMarks);
return 0;
Q2. Calculate the sum of all the elements in the given array.
#include <iostream>
int sum = 0;
sum += arr[i];
return sum;
int main() {
int arr[size];
std::cout << "Enter " << size << " elements of the array:" <<
std::endl;
std::cout << "Sum of elements in the array: " << sum <<
std::endl;
return 0;
Java
C++ &+ DSA
DSA
Q3. Find the element x in the array . Take array and x as input.
#include <iostream>
if (arr[i] == x) {
int main() {
int arr[size];
std::cout << "Enter " << size << " elements of the array:" <<
std::endl;
int x;
std::cin >> x;
if (isElementFound) {
std::cout << "Element " << x << " is found in the array."
<< std::endl;
} else {
std::cout << "Element " << x << " is not found in the
array." << std::endl;
return 0;
Q4. Find the maximum value out of all the elements in the array.
Java
C++ &+ DSA
DSA
#include <iostream>
maxVal = arr[i];
return maxVal;
int main() {
int arr[size];
std::cout << "Enter " << size << " elements of the array:" <<
std::endl;
std::cout << "Maximum value in the array: " << maxVal <<
std::endl;
return 0;
#include <iostream>
Java
C++ &+ DSA
DSA
// Ensure firstLargest is greater than secondLargest
std::swap(firstLargest, secondLargest);
secondLargest = firstLargest;
firstLargest = arr[i];
secondLargest = arr[i];
return secondLargest;
int main() {
int arr[size];
std::cout << "Enter " << size << " elements of the array:" <<
std::endl;
return 0;
Q6. Count the number of elements in given array greater than a given number x.
#include <iostream>
int count = 0;
Java
C++ &+ DSA
DSA
for (int i = 0; i < size; ++i) {
if (arr[i] > x) {
count++;
return count;
int main() {
int arr[size];
std::cout << "Enter " << size << " elements of the array:" <<
std::endl;
int x;
std::cin >> x;
std::cout << "Number of elements greater than " << x << ": "
<< count << std::endl;
return 0;
#include <iostream>
#include <vector>
if (vec[i] == x) {
Java
C++ &+ DSA
DSA
return -1; // Return -1 if x is not found in the vector
int main() {
std::vector<int> vec;
int size;
int element;
vec.push_back(element);
int x;
std::cin >> x;
if (lastOccurrence != -1) {
} else {
return 0;
Q8. Find the doublet in the Array whose sum is equal to the given value x.
#include <iostream>
#include <vector>
Java
C++ &+ DSA
DSA
// Iterate through the vector
if (vec[i] + vec[j] == x) {
std::cout << "Doublet found: (" << vec[i] << ", "
<< vec[j] << ")" << std::endl;
found = true;
if (!found) {
std::cout << "No doublet found with sum equal to " << x
<< "." << std::endl;
int main() {
std::vector<int> vec;
int size;
int element;
vec.push_back(element);
int x;
std::cin >> x;
findDoublets(vec, x);
return 0;
Q9. Write a program to copy the contents of one array into another in the reverse order.
Java
C++ &+ DSA
DSA
#include <iostream>
#include <vector>
reversed.push_back(original[i]);
int main() {
std::vector<int> originalVector;
std::vector<int> reversedVector;
int size;
int element;
originalVector.push_back(element);
copyVectorReverse(originalVector, reversedVector);
return 0;
Q10. Write a program to copy the contents of one array into another in the reverse order.
#include <iostream>
#include <vector>
size_t start = 0;
Java
C++ &+ DSA
DSA
while (start < end) {
std::swap(vec[start], vec[end]);
++start;
--end;
int main() {
std::vector<int> myVector;
int size;
int element;
myVector.push_back(element);
reverseVector(myVector);
return 0;
#include <iostream>
#include <vector>
Java
C++ &+ DSA
DSA
std::swap(arr[start], arr[end]);
++start;
--end;
int n = arr.size();
k = k % n;
reverseArray(arr, 0, n - k - 1);
reverseArray(arr, n - k, n - 1);
reverseArray(arr, 0, n - 1);
int main() {
std::vector<int> myArray;
int size;
int element;
myArray.push_back(element);
int k;
std::cin >> k;
rotateArray(myArray, k);
Java
C++ &+ DSA
DSA
std::cout << std::endl;
return 0;
#include <iostream>
#include <vector>
int left = 0;
left++;
right--;
std::swap(arr[left], arr[right]);
left++;
right--;
int main() {
std::vector<int> myArray;
int size;
int element;
myArray.push_back(element);
Java
C++ &+ DSA
DSA
}
sortZerosOnes(myArray);
return 0;
Q13. Move all negative numbers to beginning and positive to end with constant extra space.
#include <iostream>
#include <vector>
int n = arr.size();
int left = 0;
int right = n - 1;
left++;
right--;
std::swap(arr[left], arr[right]);
left++;
right--;
int main() {
std::vector<int> myArray;
Java
C++ &+ DSA
DSA
// Input elements of the array
int size;
int element;
myArray.push_back(element);
rearrangeNegativesPositives(myArray);
return 0;
#include <iostream>
#include <vector>
int low = 0;
int mid = 0;
switch (arr[mid]) {
case 0:
std::swap(arr[low], arr[mid]);
low++;
mid++;
break;
case 1:
mid++;
break;
case 2:
std::swap(arr[mid], arr[high]);
high--;
Java
C++ &+ DSA
DSA
break;
int main() {
std::vector<int> myArray;
int size;
int element;
myArray.push_back(element);
sortColors(myArray);
return 0;
#include <iostream>
#include <vector>
Java
C++ &+ DSA
DSA
void mergeSortedArrays(const std::vector<int>& arr1, const
std::vector<int>& arr2, std::vector<int>& mergedArray) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
mergedArray[k++] = arr1[i++];
mergedArray[k++] = arr2[j++];
int main() {
int size1;
std::cout << "Enter the size of the first sorted array: ";
int element;
arr1.push_back(element);
int size2;
std::cout << "Enter the size of the second sorted array: ";
int element;
Java
C++ &+ DSA
DSA
std::cout << "Element " << i + 1 << ": ";
arr2.push_back(element);
return 0;
Note :- If not possible then print the sorted order in ascending order.
#include <iostream>
#include <algorithm>
#include <vector>
if (std::next_permutation(arr.begin(), arr.end())) {
} else {
std::sort(arr.begin(), arr.end());
int main() {
std::vector<int> myArray;
Java
C++ &+ DSA
DSA
// Input elements of the array
int size;
int element;
myArray.push_back(element);
findNextPermutation(myArray);
return 0;
#include <iostream>
#include <vector>
int n = height.size();
if (n <= 2) {
leftMax[0] = height[0];
int trappedWater = 0;
Java
C++ &+ DSA
DSA
// Calculate the trapped water above each bar
return trappedWater;
int main() {
std::vector<int> height;
int size;
int h;
std::cin >> h;
height.push_back(h);
return 0;
Java
C++ &+ DSA
DSA
THANK
YOU !