Posts

Showing posts with the label stl

Implementation of Vector in c++

Image
Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container. Screenshot :  Code : #include<iostream> #include<algorithm> #include<vector> using namespace std; int main() { int t; vector<int> a; for(int i=0;i<6;i++) { int t; cin>>t; a.push_back(t); } if(a.empty()) { cout<<"Vector is empty"<<endl; return 0; } sort(a.begin(),a.end()); for(int i=0;i<6;i++) { cout<<a[i]<<" "; } cout<<"\nThe size of vector is "<<a.size(); return 0; }

Sort using algorithm header

Image
The below program takes an array as input and prints the sorted array.  The header  <algorithm>  defines a collection of functions especially designed to be used on ranges of elements.sort function takes two arguments. The arguments are the start index and end index of array. This header file does not work in c. It can be only used in C++. Output :  Code : #include<iostream> #include<algorithm> using namespace std; int main() { int n; cout<<"Enter number of elements you want to sort : "; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); for(int i=0;i<n;i++) cout<<a[i]<<" "; return 0; }

Sort using vector in c++

Image
The below program prints the input numbers in a sorted order.The program is implemented using c++. Output : Code : #include<bits/stdc++.h> using namespace std; int main() { vector<int> s; int n; cout<<"Enter number of elements : "; cin>>n; for(int i=0;i<n;i++) { int t; cin>>t; s.push_back(t); } sort(s.begin(),s.end()); cout<<"Sorted Order :"<<endl; for(int i=0;i<n;i++) cout<<s[i]<<" "; return 0; }