Skip to content

Instantly share code, notes, and snippets.

@mdshopon
Last active September 24, 2020 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdshopon/aa6a277b137002800ccbc04c335034ba to your computer and use it in GitHub Desktop.
Save mdshopon/aa6a277b137002800ccbc04c335034ba to your computer and use it in GitHub Desktop.
C++ STL Vector Examples of Various Common Functions
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Basic Declaration */
// vector<int> vec_1(5);
// vector<int> vec_2(4,10);
// vector<int> vec_3{1,2,3,4,5};
// vector<int> vec_4;
// vec_4.push_back(10);
// int N,M;
// cin>>N;
// vector<int> vec_5;
// for(int i=0;i<N;i++){
// cin>>M;
// vec_5.push_back(M);
// }
/* How to Access Vector Elements */
// vector<int> vec(10);
// cout<<vec[0];
// for(int i=0;i<vec.size;i++){
// cout<<vec[i];
// }
// cout<<vec.front()<<endl;
// cout<<vec.back()<<endl;
/* How to copy elements from one vector to another */
// vector<int> vec_1{1,2,3,4,5};
// vector<int> vec_2(vec_1);
/* How to insert elements in Vector */
// vector<int> vec_1{1,2,3,4,5};
// vec_1.insert(vec_1.begin(),30);
// vec_1.inser(vec_1.begin(),3,10);
// vec_1.insert(vec_1.begin(),{1,2,3,4});
// vector<int> vec_2;
// vec_1.insert(vec_1.begin(),vec_2.begin(),vec_2.end());
/* Erase Elements from the Vector */
// vector<int> vec_1{10,20,30,40,50};
// vec_1.erase(vec_1.begin(),vec_1.begin()+2);
// vec_1.pop_back();
/* Reverse a vector */
//reverse(vec_1.begin(), vec_1.end());
/* How to search on Vectors */
// vector<int> vec_1 { 10, 20, 30, 40 };
// auto it = find(vec_1.begin(),vec_1.end(),21);
// int position = it-vec_1.begin();
/* Find if a Vector exist in another vector or not */
// vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7 };
// vector<int> v2 = { 3, 4, 5 };
// auto i1 = std::search(v1.begin(), v1.end(), v2.begin(), v2.end());
// // checking if iterator i1 contains end pointer of v1 or not
// if (i1 != v1.end()) {
// cout << "vector2 is present at index " << (i1 - v1.begin());
// } else {
// cout << "vector2 is not present in vector1";
// }
/* Binary Search on C++ STL */
vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7 };
int pos = binary_search(arr.begin(), arr.end(), 15)
cout<<pos<<endl; // If exist will return 1
/* Checking Upper or lower bound. It means checking the first and last occurance of a particular value */
vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7 };
// auto low_pos = lower_bound(v1.begin(),v1.end(),3);
// auto upr_pos = upper_bound(v1.begin(),v1.end(),3);
// cout<< low_pos-v1.begin()<<endl;
// cout<< upr_pos-v1.begin()<<endl;
/* Sort a Vector */
// vector<int> vec_1 ={10,2,41,15};
// // Ascending Order
// sort(vec_1.begin(),vec_2.end());
// //Descending Order
// sort(vec_1.begin(),vec_2.end(),greater<int>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment