Vectors, like one-dimensional arrays, store elements in a contiguous manner, i.e., the elements are stored in memory side by side. The difference lies in that vectors are dynamic; hence their size can change on demand.
Imagine it this way: you have a series of boxes connected together. Once all these boxes are used up, you would usually transfer all your things to a new, larger box. But not with vectors!
With vectors, you can simply glue together another box and add your things in that. In a similar manner, if you’ve taken things out of some boxes and no longer need them, you can simply remove them altogether and avoid wasting space, as opposed to transferring your things to a new smaller box.
#include <iostream>#include <vector>using namespace std;int main() {vector<int> numbers;numbers.resize(7);cout<<numbers.size()<<endl;numbers.resize(4);cout<<numbers.size();}
#include <iostream>#include <vector>#include <string>using namespace std;int main() {//Initialized a vectorvector<string> colours;colours.push_back("white");colours.push_back("red");colours.push_back("purple");colours.push_back("blue");//Adding the white boxcolours.push_back("white");//Printing the last elementcout<<colours[4]<<endl;}
#include <iostream>#include <vector>#include <string>using namespace std;int main() {// your code goes here//Initialized a vectorvector<string> colours;colours.push_back("white");colours.push_back("red");colours.push_back("purple");colours.push_back("blue");colours.push_back("white");//Removing the last elementcolours.pop_back();//The last element should be the blue boxcout<<colours[3]<<endl;}
#include <iostream>#include <vector>#include <string>using namespace std;int main() {// your code goes here//Initialized a vectorvector<string> colours;colours.push_back("white");colours.push_back("red");colours.push_back("blue");colours.push_back("purple");//The answer should be whitecout<<colours.front()<<endl;//The answer should be purplecout<<colours.back()<<endl;}
Free Resources