Skip to content

Instantly share code, notes, and snippets.

@mubbashir10
Last active February 10, 2023 05:13
Show Gist options
  • Save mubbashir10/0ffd5a9acdb544521564 to your computer and use it in GitHub Desktop.
Save mubbashir10/0ffd5a9acdb544521564 to your computer and use it in GitHub Desktop.
Simple example of vectors in C++ (size, adding elements, traversing)
/*
About: A simple tutorial of using vectors (c++ STL)
Author: Mubbashir10
URL: http://mubbashir10.com
*/
//libraries
#include <iostream>
#include <vector>
//defining namespace
using namespace std;
//main function
int main(){
//declaring vector
vector <int> machar;
//printing size
cout<<"Size of machar before adding elements "<<machar.size()<<endl;
//adding elements
machar.push_back(1);
machar.push_back(2);
machar.push_back(3);
machar.push_back(4);
machar.push_back(5);
//printing size
cout<<"Size of machar after adding elements "<<machar.size()<<endl;
//printing elements
cout<<"Elements of machar (via index) "<<endl;
cout <<machar[0]<<endl;
cout <<machar[1]<<endl;
cout <<machar[2]<<endl;
cout <<machar[3]<<endl;
cout <<machar[4]<<endl;
//traversing
cout<<"Elements of machar (via iterator) "<<endl;
vector<int>::iterator point;
point = machar.begin();
while(point!=machar.end()){
cout<<point[0]<<endl;
point++;
}
//exiting
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment