warning: use using namespace std:
i always use 1st based indexing
Introduction
#include <vector>
⛓ Vectors are arrays with super power (part of STL). You can sort it, push, pull data with just in-built(not recommended) functions.🧡🧡 It has one more superpower it size is very dynamic which means you can push any number of items even after size is specified.🧡 It just double the vector size.
initial size
(after adding) after size
0
1
2
4
note: Drawback of these vector is that memory wasteage. (getaway: always know no of items).
Syntax
Declaration
Usually you wont be needing vector without int(mainly).🧡
//(size,value)
//std::vector<datatype> arr_name(size);
std::vector<int> file(5,12) // 5 elements with each 12
std::vector<int> v(100); // Initializes 100 elements with zeros
std::vector<int> v(existingVector) //create a copy of existingVector
// (initialize with zero size)
// std::vector<string> name;
std::vector<string> str; //contains string value
std::vector<bool> str2; //contains bool value
std::vector<float> data = {1,2,3,4,5}; //vector with 5 value
built-in functions
import following header
#include <algorithm>
initial vector
std::vector<int> v = {1,5,4,3,2}
begin and end function
These are the pointer use to point the first and last element address
auto last = v.end();
cout<<“first: “<<*first<< ” “<<“last: “<<*last<<ednl;
output
SORT function
std::vector<int> v = {1,5,4,3,2};
std::sort(v.begin(),v.end())
std:sort(v.begin(),v.end(),std::greater<int>());
// method 2
//reverse iterator
//use reverse iterator function
//reverse iterator allows you to traverse vector in reverse order
std::sort(v.rbegin(),v.rend())
output
5 4 3 2 1
Size function
know the no of elements in an array.
push_back function
append item at the end of the array
v.push_back(5)
output
pop_back function
remove the last item from vector
output
back front function
returns the last element
v.front() //1
insert function
insert item at given position
//v.insert(position_pointer,size,value);
// Insert 100 at position 4th (using an iterator)
std::vector<int>::iterator it = myVector.begin() + 3;
//(alternative)auto it = myVector.begin() + 3;
myVector.insert(it,1,100);
output
erase function
This function helps erase element from specific position.
v.erase(v.begin()) //remove the first element
v.erase(v.begin() + 1) //remove 2nd element
v.erase(v.end()) //revome last element
note:erase function always expect normal iterator
auto itlast = v.rbegin();
itlast++; // increase the iterator
v.erase(itlast.base()) // remove second last element
note: convert the reverse iterator to normal one.
resize function
You can resize vector
clear function
You can clear function to remove all elements
empty function
if(v.empty())
cout<<“yes”<<endl;
Ranged base loop
traverse vector using for loop
cout << num << ” “;
}
Accessing Values
put the index you want to access
Github ❤
❤Please follow for more such content on dev: @aryan015