Prerequisite – Vector Basics
Following are some important points that can save time on little things in an interview or an important coding contest.
-
vector <int> vect(10) vs vector<int> vect[10]
// Creates a vector vect[] of size 10 vector <int> vect(10) // creates an array of vectors vect[] of size // 10 where each vector has int members vector<int> vect[10]
-
resize() and push_back():
After the resize() function has been used on a vector, if push_back() is used on the same vector, the elements being pushed back get added at the end of the resized vector, and not into it.// A C++ program to demonstrate that push_back()
// happens at the end of resized vector.
#include<bits/stdc++.h>
using
namespace
std;
int
main()
{
vector<
int
> vect;
for
(
int
i = 0; i < 5; i++)
vect.push_back(i);
// Resizing vector to size 10
vect.resize(10);
// Prints 0 1 2 3 4 0 0 0 0 0
for
(
int
i = 0; i < vect.size(); i++)
cout << vect[i] <<
" "
;
cout <<
"\n"
;
vect.push_back(50);
// Prints 0 1 2 3 4 0 0 0 0 0 50
for
(
int
i = 0; i < vect.size(); i++)
cout << vect[i] <<
" "
;
return
0;
}
Output: 0 1 2 3 4 0 0 0 0 0 0 1 2 3 4 0 0 0 0 0 50
- clear() function It makes the vector to have zero elements, i.e- no elements and not making the elements to all 0s.
- Creating a two dimensional vector
// This doesn't work vector<vector<int>> vect; // This works fine vector< vector <int> > vect;
The difference between these two statements is that the first statement has a space between the angular brackets ( > >). Writing without the space doesn’t work because >> is an operator in C++.
-
Passing vectors to functions:
When a vector is simply passed to a function, a copy of the vector is created. This might take a lot of time in cases of large vectors.// C++ program to demonstrate that when vectors
// are passed to functions without &, a copy is
// created.
#include<bits/stdc++.h>
using
namespace
std;
// The vect here is a copy of vect in main()
void
func(vector<
int
> vect)
{
vect.push_back(30);
}
int
main()
{
vector<
int
> vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
// vect remains unchanged after function
// call
for
(
int
i=0; i<vect.size(); i++)
cout << vect[i] <<
" "
;
return
0;
}
Output :
10 20
In situations where we don’t actually need to have a copy of the vector, the declaration should be made as follows:
// It is recommended to pass vectors by reference // wherever possible. int func(vector<int>& vect) { }