CodeISM Class 4 (STL Pair, Sort, Structure)
CodeISM Class 4 (STL Pair, Sort, Structure)
in C++
pop_back() in vector
- Removes the last element of a vector
sort()
Time Complexity = O(n log n )
vec:={5,1,7,3,4,9}
syntax-> sort(starting_iterator, ending_iterator)
starting_iterator-> vec.begin();
ending_iterator-> vec.end();
Example
sort(vec.begin(),vec.end());
swap()
Example:
int a=5;
int b=6;
swap(a,b);
cout<<a<<endl;
cout<<b<<endl;
sort(vec.begin(),vec.end()); // {1,2,3,4,8}
reverse(vec.begin(),vec.end()); // {8,4,3,2,1}
Struct
Code-1
#include <bits/stdc++.h>
using namespace std;
struct Freshers{
string name;
string AdmNo;
int age;
double height;
};
// structure definition ends with a semicolon (;)
int main(){
Freshers fresher;
fresher.name = "Manyank";
fresher.AdmNo = "20JE0655";
fresher.age = 18;
fresher.height = 6.1;
Code-2
#include <bits/stdc++.h>
using namespace std;
struct Point{
int x;
int y;
};
int main(){
Point point[n];
for(int i=0;i<n;i++)
cin>>point[i].x>>point[i].y;
(x1,y1);
(x2,y2);
(x3,y3);
...
(xn,yn);
int X[n];
int Y[n];
for(int i=0;i<n;i++) cin>>X[i]>>Y[i];
(xi,yi);
cout<<X[i]<<" "<<Y[i]<<endl;
return 0;
}
Pair in C++ STL
#include <bits/stdc++.h>
using namespace std;
int main(){
pair<int,int> point;
cin>>point.first>>point.second;
cout<<point.first<<" "<<point.second<<endl;
pair<string,double> Fresher;
cin>>Fresher.first;
cin>>Fresher.second;
return 0;
}
Point in 3D->
#include <bits/stdc++.h>
using namespace std;
int main(){
pair<int,pair<int,int>> point3D;
// x-> point3D.first;
// y-> point3D.second.first;
// z-> point3D.second.second;
return 0;
}
Link:
https://www.hackerrank.com/challenges/equality-in-a-
array/problem
(First, try it by yourself, then only look at the solution
below)
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n]; // 3 1 1 2 2 2 3 3 3
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n); // 1 1 2 2 2 3 3 3 3
int ans = 10000;
for(int i=0;i<n;i++){
int freq=0;
int com = a[i];
while(i<n&&a[i]==com){
freq++;
i++;
}
i--;
ans = min(ans,n-freq);
}
cout<<ans;
}
https://atcoder.jp/contests/abc187/tasks/abc187_d