vector
Initialising vector
Different ways to initialise a Vector
vector<int> v1;
vector<int> v2(n);
vector<int> v3(n, 2); //{2,2,2,2,2,2,2}
vector
from vector
vector<int> vec(vecName.begin(), vecName.end());
Only problem in above code is it can only be used during Initialisation not to update existing vector
vector
from deque
vector<int> vec(dequeName.begin(), dequeName.end());
Only problem in above code is it can only be used during Initialisation not to update existing vector
vector
from set
vector<int> vec(setName.begin(), setName.end());
Only problem in above code is it can only be used during Initialisation not to update existing vector
Copy the vector
or deque
elements to another vector
or deque
using insert()
// vector "vec" is given
deque<int> dq; // empty "deque" initialised
dq.insert(dq.end(), vec.begin(), vec.end());
deque
to vector
// deque "dq" is given
vector<int> vec; // empty "deque" initialised
vec.insert(vec.end(), dq.begin(), dq.end());
array
to vector
:::
Taking unknown number of User Inputs
for one vector
vector<int> v;
int temp;
vector<int> v;
while (cin >> temp)
{
v.emplace_back(temp);
}
Taking input for multiple vectors
from multiple single lines
Using istringstream
/* Inputs are
10 22 2 1 5 54 16651 6516 6165 2
65 6565 65 65 56 6565
*/
// #include <sstream> ~ "<sstream>" contains "istringstream"
// #include <string>
vector<int> v1;
vector<int> v2;
int tmp; // "tmp" will be used to store the "integers" from the "istingstream"
string str1, str2; // declaring the "strings" where to "store the lines"
// Initialising the string👇
getline(cin, str1); // "str1" becomes 👉 [ 10 22 2 1 5 54 16651 6516 6165 2 ]
getline(cin, str2); // "str2" becomes 👉 [ 65 6565 65 65 56 6565 ]
istringstream ss1(str1); // 👉 ASSIGNING THE STRING "str1" to 'istringstream' "ss1"
// Giving the inputs to the vector "al1" // Initialising "al1"👇
while (ss1 >> tmp) {
v1.emplace_back(tmp);
} // "v1" becomes 👉 [ 10 22 2 1 5 54 16651 6516 6165 2 ]
istringstream ss2(str2); // 👉 ASSIGNING THE STRING "str2" to 'istringstream' "ss2"
// Giving the inputs to the vector "al2" // Initialising "al2"👇
while (ss2 >> tmp) {
v2.emplace_back(tmp);
} // "v2" becomes 👉 [ 65 6565 65 65 56 6565 ]
- Output is 👇
v1
10 22 2 1 5 54 16651 6516 6165 2
v2
65 6565 65 65 56 6565
😱Single Input First, then vector
input😱
If the single inputs are given in the lines above the vector
then must add :~ String line;
-- getline(cin, line);
where line
will take the ending ""
from the line of the sigle Input will before taking the NEXT LINE
as input for vector
.
- Otherwise the first vector
v1
will only get""
i.e.NOTHING
🤯😡
// #include <bits/stdc++.h>
#include <algorithm>
#include <vector>
#include <climits>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
#define ll long long
#define endl "\n"
int main()
{
vector<int> v1;
vector<int> v2;
int tmp; // "tmp" will be used to store the "integers" from the "istingstream"
string str1, str2; // declaring the "strings" where to "store the lines"
int num1;
cin >> num1;
cout << num1;
cout << endl;
string line;
getline(cin, line);
// Initialising the string👇
getline(cin, str1); // "str1" becomes 👉 [ 10 22 2 1 5 54 16651 6516 6165 2 ]
cout << "str1" << str1 << endl;
getline(cin, str2); // "str2" becomes 👉 [ 65 6565 65 65 56 6565 ]
cout << "str2" << str2 << endl;
istringstream ss1(str1); // 👉 ASSIGNING THE STRING "str1" to 'istringstream' "ss1"
// Giving the inputs to the vector "al1" // Initialising "al1"👇
while (ss1 >> tmp)
{
v1.emplace_back(tmp);
} // "v1" becomes 👉 [ 10 22 2 1 5 54 16651 6516 6165 2 ]
istringstream ss2(str2); // 👉 ASSIGNING THE STRING "str2" to 'istringstream' "ss2"
// Giving the inputs to the vector "al2" // Initialising "al2"👇
while (ss2 >> tmp)
{
v2.emplace_back(tmp);
} // "v2" becomes 👉 [ 65 6565 65 65 56 6565 ]
cout << "v1" << endl;
for (auto el : v1)
{
cout << el << " ";
}
cout << endl;
cout << "v2" << endl;
for (auto el : v2)
{
cout << el << " ";
}
cout << endl;
int num2;
cin >> num2;
cout << num2;
return 0;
}
- Output is👇
56
str1 10 22 2 1 5 54 16651 6516 6165 2
str2 65 6565 65 65 56 6565
v1
10 22 2 1 5 54 16651 6516 6165 2
v2
65 6565 65 65 56 6565
45
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//taking the vector size from the user
int n;
cin >> n;
//Different ways to initialise a Vector
vector<int> v1;
vector<int> v2(n);
vector<int> v3(n, 2); //{2,2,2,2,2,2,2}
//Ways to give values to the vector
for (int i = 0; i < n; i++) {
int val;
cin >> val;
v1.emplace_back(val); //push_back can also be used
}
for (int i = 0; i < v2.size(); i++) {
cin >> v2.at(i);
//cin>>v2[i]; also can be used
}
//using iterator which I don't know
//to be leart later using iterator and pointer
//WAYS TO PRINT THE VECTOR
//my favourite method
for (auto el : v1)
cout << el << " ";
cout << endl;
for (int i = 0; i < n; i++) {
cout << v1.at(i) << " ";
//cout<<v1[i]<<" ";
}
//using iterator which I don't know
//to be learnt later using iterator and pointer
return 0;
}
Printing the vector
//my favourite method
for (auto el : v1)
cout << el << " ";
Printing 2D vector
// vector< vector<int> > v
for (auto el : v) {
for (auto el2 : el) {
cout << el << " ";
}
cout << endl;
}
Using Iterator
to be added
2D vectors
Initialising 2D vector
- Only Declaration
vector<vector<int>> v;
- Initialisation with both
ROW
andCOLUMN
vector<vector<int>> v(n, vector<int>(m)); // ROW = "n" ; COL = 'm'
vector<vector<int>> v(n, vector<int>(m, 0)); // ROW = "n" ; COL = 'm'
// Each Col of each Row will be initsialised with "0" from (m, 0) above
/*
0 0 0 0
0 0 0 0
0 0 0 0
*/
v.at(i).at(j) = temp;
- Here all elements need to be replaced like this: ⏩
v.at(i).at(j) = temp;
- Initialising with only
ROW
vector<vector<int>> v(n); // ROW = "n"
Taking user input with ROW
& COL
known
Here ROW
must be initialised as vector<vector<int>> v(row);
Otherwise the code will show
Runtime Error
:~SIGABRT
~terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
/* Input is:-
4
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
*/
int row, col = 6; // "ROW" & "COLUMN" known
cin >> row;
cout << row << " " << col << endl;
vector<vector<int>> v(row); // Initialising 2D vector
for (int i = 0; i < row; i++)
{
// v.at(i) == vector<int>(col); // NOT REQUIRED
for (int j = 0; j < col; j++)
{
int tmp;
cin >> tmp;
(v.at(i)).emplace_back(tmp);
}
}
// Printing "2D Vector"
for (auto el : v) // "( vector<int> el : v )" can also be used, "auto" just makes it easier
{
for (auto el2 : el) // "( int el2 : el )" can also be used, "auto" just makes it easier
{
cout << el2 << " ";
}
cout << endl;
}
Another method (But not a very good method)
ROW
need not be initialisedL:~vector<vector<int>> v;
- Creating a
vector<int> tempVector;
and taking the InputLINES
into thetempVector
- Then adding the
v.emplace_back(tempVector);
to the main vectorv
; So that we will not need to call any index of vectorv
likev.at(i)
because vectorv
is a 2D vector and to access the "COLUMN" part of 2D Vector "ROW" must be initialsised likevector<vector<int>> v(row);
/* Input is:-
4
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
*/
int row, col = 6;
cin >> row;
cout << row << " " << col << endl;
vector<vector<int>> v;
for (int i = 0; i < row; i++)
{
vector<int> tempVector;
for (int j = 0; j < col; j++)
{
int tmp;
cin >> tmp;
tempVector.emplace_back(tmp);
}
v.emplace_back(tempVector);
}
for (auto el : v)
{
for (auto el2 : el)
{
cout << el2 << " ";
}
cout << endl;
}
Taking user input with COL
unknown || Varying COLUMNs
~ sstream
ROW
is REQUIRED
Here ROW
must be initialised as vector<vector<int>> v(row);
Otherwise the code will show
Runtime Error
:~SIGABRT
~terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
/* Input is:-
4
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
*/
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int row; // "Column" not given
cin >> row;
// cout << row << endl;
vector<vector<int>> v(row);
string line;
getline(cin, line);
string str;
int temp;
for (int i = 0; i < row; i++)
{
getline(cin, str);
istringstream ss(str);
while (ss >> temp)
{
(v.at(i)).emplace_back(temp);
}
// istringstream.swap(ss); /* 👉 It is used only when we want to "RESET" the "istringstream ss(str);" ; So that it can be used again and another variable of "istringstream ss(str);" wil not be needed */
// 👆 But in this case we are using "FOR" or "WHILE" loops, so "istringstream ss(str);" gets "RESET" in each loop; Hence istringstream.swap(ss); is not required
}
for (auto el : v)
{
for (auto el2 : el)
{
cout << el2 << " ";
}
cout << endl;
}
return 0;
}
Taking user input with ROW
unknown ~ istringstream
ROW
or COLUMN
NOT NEEDED
Using istringstream
from <sstream>
header
ROW
need not be initialisedL:~vector<vector<int>> v;
So it will without taking anyROW
as INPUT
- Creating a
vector<int> tempVector;
and taking the InputLINES
into thetempVector
- Then adding the
v.emplace_back(tempVector);
to the main vectorv
; So that we will not need to call any index of vectorv
likev.at(i)
because vectorv
is a 2D vector and to access the "COLUMN" part of 2D Vector "ROW" must be initialsised likevector<vector<int>> v(row);
- ☠️ If the single inputs are given in the lines above the vector then must add :~
String line;
--getline(cin, line);
where line will take the ending "" from the line of the sigle Input will before taking theNEXT LINE
as input for vector. Otherwise the first vector v1 will only get "" i.e. NOTHING 🤯😡
/* Input is:-
4
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
*/
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int row;
cin >> row; // "ROW" is Not Required". 🤪But need to take as Its given,,but will NOT USE😉. "COLUMN" is not given and also NOT REQUIRED
vector<vector<int>> v;
string line; //👉 If the single inputs are given in the lines above the vector then must add :~ String line; -- getline(cin, line); where line will take the ending "" from the line of the sigle Input will before taking the NEXT LINE as input for vector.
getline(cin, line); // ## Otherwise the first vector v1 will only get "" i.e. NOTHING 🤯😡
string str; // it's the string which will store the Input "LINES"
int temp; // "tmp" will be used to store the "integers" from the "istingstream"
while (getline(cin, str)) //🤪 using while loop to traverse without needing "ROW" as Input.🤯Here "getline(cin, str)" will give input to "str" and will also "END / Terminate" the "while loop" when there is no input is left
{
istringstream ss(str);
vector<int> tempVector;
while (ss >> temp)
{
tempVector.emplace_back(temp);
}
v.emplace_back(tempVector);
// istringstream.swap(ss); /* 👉 It is used only when we want to "RESET" the "istringstream ss(str);" ; So that it can be used again and another variable of "istringstream ss(str);" wil not be needed */
// 👆 But in this case we are using "FOR" or "WHILE" loops, so "istringstream ss(str);" gets "RESET" in each loop; Hence istringstream.swap(ss); is not required
}
for (auto el : v)
{
for (auto el2 : el)
{
cout << el2 << " ";
}
cout << endl;
}
return 0;
}
Taking user input with both ROW
and COLUMN
unknown ~ istringstream
ROW
or COLUMN
NOT NEEDED
Using istringstream
from <sstream>
header
ROW
need not be initialisedL:~vector<vector<int>> v;
So it will without taking anyROW
as INPUT
- Creating a
vector<int> tempVector;
and taking the InputLINES
into thetempVector
- Then adding the
v.emplace_back(tempVector);
to the main vectorv
; So that we will not need to call any index of vectorv
likev.at(i)
because vectorv
is a 2D vector and to access the "COLUMN" part of 2D Vector "ROW" must be initialsised likevector<vector<int>> v(row);
- ☠️ If the single inputs are given in the lines above the vector then must add :~
String line;
--getline(cin, line);
where line will take the ending "" from the line of the sigle Input will before taking theNEXT LINE
as input for vector. Otherwise the first vector v1 will only get "" i.e. NOTHING 🤯😡
/* Input is:-
4
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
*/
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int row;
cin >> row; // "ROW" is Not Required". 🤪But need to take as Its given,,but will NOT USE😉. "COLUMN" is not given and also NOT REQUIRED
vector<vector<int>> v;
string line; //👉 If the single inputs are given in the lines above the vector then must add :~ String line; -- getline(cin, line); where line will take the ending "" from the line of the sigle Input will before taking the `NEXT LINE` as input for vector.
getline(cin, line); // ## Otherwise the first vector v1 will only get "" i.e. NOTHING 🤯😡
string str; // it's the string which will store the Input "LINES"
int temp; // "tmp" will be used to store the "integers" from the "istingstream"
while (getline(cin, str)) //🤪 using while loop to traverse without needing "ROW" as Input.🤯Here "getline(cin, str)" will give input to "str" and will also "END / Terminate" the "while loop" when there is no input is left
{
istringstream ss(str);
vector<int> tempVector;
while (ss >> temp)
{
tempVector.emplace_back(temp);
}
v.emplace_back(tempVector);
// istringstream.swap(ss); /* 👉 It is used only when we want to "RESET" the "istringstream ss(str);" ; So that it can be used again and another variable of "istringstream ss(str);" wil not be needed */
// 👆 But in this case we are using "FOR" or "WHILE" loops, so "istringstream ss(str);" gets "RESET" in each loop; Hence istringstream.swap(ss); is not required
}
for (auto el : v)
{
for (auto el2 : el)
{
cout << el2 << " ";
}
cout << endl;
}
return 0;
}
Sub vector
TO DO
vector
in built Methods
Replace an element of a vector at()
// "v" is: [ 10 20 30 40 50 60 ]
v.at(3) = 2222; // replace Index='3' with "2222" // replaced "40" with "2222"
// "v" becomes: [ 10 20 30 2222 50 60 ]
v.size()
cout << v.size();
vector begin()
1st iterator
vector end()
after last iterator
v.end()
is not included as it doesnt't exists in(v.begin(), v.end())
vector rbegin()
returns a reverse iterator pointing to the last element in the container. i.e. it points to the index
size() - 1
or we can sayv.end() - 1
for (auto it = v.rbegin(); it != v.rend(); it++)
{
cout << *it << " ";
}
vector rend()
::caution
returns a reverse iterator pointing to the theoretical element right before the first element in the vector container. i.e. it points to the index
0
or we can sayv.begin()
v.rend() is excluded in (v.rbegin(), v.rend())
for (auto it = v.rbegin(); it != v.rend(); it++)
{
cout << *it << " ";
}
:::
back()
v.back()
is used to access the last element of the vector.v.back()
is same asv.at(v.size() - 1)
/* vector<vector<int>> ans; */ /* vector<vector<int>>& v */
if (ans.back().at(1) >= vect[i][0])
{
ans.back().at(1) = max( ans.back().at(1), vect[i][1] );
}
front()
v.back()
is used to access the first element of the vector.v.front()
is same asv.at(0)
emplace_back()
v2.emplace_back(tmp);
at()
cout << vec.at(i) << endl;
insert()
Inserts elements at the specified location in the container (vector
).
v.insert(v.begin() + IndexNo)
inserts an element at the Index No.insert()
function adds the element to vector and the elements at thatIndex No.
gets pused back to the right side.
// Input is: [ 1 2 3 4 5 6 7 ]
v.insert(v.begin() + 2, 555); // element at that `Index No` gets pused to the right side
// Output: [ 1 2 555 3 4 5 6 7 ]
// "v" = [ 1 2 3 4 5 6 7 ]
// "v1" = [ 100 200 300 400 500 600 700 ]
v.insert(v.begin() + 5, v1.begin(), v1.end()); // elements at that `Index No` gets pused to the right side
// Inserted " 100 200 300 400 500 600 700 " at Index="5"
// Output is: [ 1 2 3 4 5 100 200 300 400 500 600 700 6 7 ]
// Index are :~ 0 1 2 3 4 5 6 7 8 9 10 11 12 13
Copy the vector
or deque
elements to another vector
or deque
using insert()
add vector
to deque
// vector "vec" is given
deque<int> dq; // empty "deque" initialised
dq.insert(dq.end(), vec.begin(), vec.end());
add deque
to vector
// deque "dq" is given
vector<int> vec; // empty "deque" initialised
vec.insert(vec.end(), dq.begin(), dq.end());
emplace()
Only availablde for single insertions,NOT VALID for range insertions operations like adding deque
elements to vector
is not AVAILABEL in emplace()
;; but these are available in insert()
When to use emplace()
:
- Single insertion of single elements at certain positions
When to use insert()
:
- Range of elements like
vector
todeque
and so on.
TO ADD
- emplace() vs insert()
assign()
erase()
erase(int position)
: Removes the element present at position. Ex:v.erase(v.begin()+4);
(erases the fifth element of the vector v)
// Input is [ 10 5 2 3 10 ]
// To remove/erase Index = "1"
cin >> temp; // temp = 1
v.erase(v.begin() + temp); // v.erase(1)
// output is: [ 10 2 3 10 ] // 5 at Index=1 has been erased/removed
erase(int start,int end)
: Removes the elements in the range from start to end; inclusive of the start and exclusive of the end. Ex:v.erase(v.begin()+2,v.begin()+5);
(erases all the elements from the 3rd element to the 4th element not the 5th element.)
// Input is [ 100 90 80 70 40 10 56 ]
// To remove/erase Index="2" to Index="5"
cin >> num1 >> num2; // num1 = 2 , num1 = 5
v.erase(v.begin() + num1, v.begin() + num2); // v.erase(2, 5)
// output is: [ 100 90 10 56 ] // [ 80 70 40 ] has been erased/removed
clear()
- clears the complete
container
- After using this method the container becomes empty.
// vec => {1 2 3 4 5 6}
vec.clear();
// 🔼 vec => { } /* empty */
pop_back()
empty()
v.empty()
return bool true or false
--
methods only available to vector
capacity()
reserve()
data()
vector specific solution tricks
erase element by value
first
find(..)
thenv.erase()
auto it = find(v2.begin(), v2.end(), el); // iterator
if (it != v2.end())
{
v2.erase(it); // erase takes iterators like .. 'v.begin() + 2'
}
remove all occurances of an element
remove(v.begin(), v.end(), "hello");