Uploaded by Tawhid Monowar

STL CPP

advertisement
Common Libraries
Functions
#include<algorithm>
#include<functional> // for hash
#include<climits> // all useful constants
#include<cmath>
#include<cstdio>
#include<cstdlib> // random
#include<ctime>
#include<iostream>
#include<sstream>
#include<iomanip> // right justifying std::right and std::setw(width)
#include<bits/stdc++.h>
using namespace std;
Data Structure
#include<deque> // double ended queue
#include<list>
#include<queue> // including priority_queue
#include<stack>
#include<string>
#include<vector>
Data type range
Data Type
Size (in bytes)
int
4
long int
4
long long
8
float
4
double
8
long double
12
Range
ASCII Table
Bitwise Operators
Bitwise operators can only be used alongside char and int data types.
Description
Operator
Bitwise AND Operator
&
Bitwise OR Operator
|
Bitwise XOR Operator
^
Bitwise Complement Operator
~
Number System
Decimal to binary
long long convert(int n) {
long long bin = 0;
int rem, i = 1;
while (n!=0) {
rem = n % 2;
n /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}
Binary to Decimal
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n!=0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
Structures
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
cin >> p1.age;
cout << p1.age;
}
Vector
Vectors are the same as dynamic arrays with the ability to resize itself automatically.
Element access
at()
access specific elements with bounds checking.
operator[]
access specific elements.
front()
access the first element.
back()
access the last element.
Capacity
empty()
checks whether the container is empty.
size()
returns the number of elements.
capacity()
returns the number of elements that can be held.
shrink_to_fit()
reduces memory usage by freeing unused memory.
Modifiers
clear()
clears the contents.
insert()
inserts elements.
erase()
erases elements.
push_back()
adds an element to the end.
pop_back()
removes the last element.
resize()
changes the number of elements stored.
swap()
swaps two vectors.
iter_swap()
swaps two elements.
Deque
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends.
Element access
at()
access specific elements with bounds checking.
operator[]
access specific elements.
front()
access the first element.
back()
access the last element.
Capacity
empty()
checks whether the container is empty.
size()
returns the number of elements.
capacity()
returns the number of elements that can be held.
shrink_to_fit()
reduces memory usage by freeing unused memory.
Modifiers
clear()
clears the contents.
insert()
inserts elements.
erase()
erases elements.
push_back()
adds an element to the end.
push_front()
inserts an element to the beginning.
pop_back()
removes the last element.
pop_front()
removes the first element.
resize()
changes the number of elements stored.
swap()
swaps two deque.
iter_swap()
swaps two elements.
List
Lists are sequence containers that allow constant time insert and erase operations anywhere within the
sequence, and iteration in both directions.
Element access
front()
access the first element.
back()
access the last element.
Capacity
empty()
checks whether the container is empty.
size()
returns the number of elements.
Modifiers
clear()
clears the contents.
insert()
inserts elements.
erase()
erases elements.
push_back()
adds an element to the end.
push_front()
inserts an element to the beginning.
pop_back()
removes the last element.
pop_front()
removes the first element.
resize()
changes the number of elements stored.
swap()
swaps two lists.
iter_swap()
swaps two elements.
Operations
merge()
merges two lists.
splice()
moves elements from another list. (3 way to move)
remove()
removes elements satisfying specific criteria.
reverse()
reverses the order of the elements.
unique()
removes consecutive duplicate elements.
sort()
sorts the elements.
Queue
queue class is a container adaptor that gives the programmer the functionality of a queue - specifically, a FIFO
data structure.
Element access
front()
access the first element.
back()
access the last element.
Capacity
empty()
checks whether the container is empty.
size()
returns the number of elements.
Modifiers
push()
inserts element at the end.
pop()
removes the first element.
Priority Queue
A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element,
at the expense of logarithmic insertion and extraction.
Element access
top()
accesses the top element
Capacity
empty()
checks whether the container is empty.
size()
returns the number of elements.
Modifiers
push()
inserts element at the end.
pop()
removes the first element.
Stack
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is
added at one end (top) and an element is removed from that end only.
Element access
top()
accesses the top element
Capacity
empty()
checks whether the container is empty.
size()
returns the number of elements.
Modifiers
push()
inserts element at the end.
pop()
removes the first element.
Set / Multiset
Sets are containers that store unique elements following a specific order, in multiset multiple elements can
have the same values.
Capacity
empty()
checks whether the container is empty.
size()
returns the number of elements.
Modifiers
clear()
clears the contents.
insert()
inserts elements.
erase()
erases elements.
swap()
swaps two sets.
Operations
find()
get iterator to element.
count()
count elements with a specific value.
lower_bound()
Return iterator to lower bound.
upper_bound()
Return iterator to upper bound.
equal_range()
Get a range of equal elements.
Iterators
Iterators are used to point at the memory addresses of STL containers
begin()
returns an iterator to the beginning.
end()
returns an iterator to the end.
rbegin()
returns a reverse iterator to the beginning.
rend()
returns a reverse iterator to the end.
advance()
Using advance() to increment iterator position.
Pair
Pair is used to combine together two values that may be different in type.
Member variables
first
The first value in the pair
second
The second value in the pair
Member Functions
make_pair()
Construct pair object
swap()
Exchanges the contents of two pairs
tie()
Tuple element type for pair
get ()
Get element
String
Strings are objects that represent sequences of characters.
Input
cin >>
Single word input.
getline(cin,str)
Full line input.
Element access (Iterators available)
at() or [ ]
Get character of string
back()
Access last character
front()
Access first character
Capacity
size() or length()
Return length of string
empty()
checks whether the string is empty.
capacity()
returns the number of elements that can be held.
Modifiers
+= or append()
Append to string
push_back()
Append character to string
insert()
Insert into string
erase()
erases elements.
replace()
Replace portion of string
swap()
swaps two string.
iter_swap()
swaps two elements.
pop_back()
Delete last character
clear()
clears the contents.
String operations
substr()
Generate substring.
compare()
Compare strings.
copy()
Copy sequence of characters from string
find()
Find content in string
rfind()
Find last occurrence of content in string
find_first_of()
Find character in string
find_last_of()
Find character in string from the end
find_first_not_of()
Find absence of character in string
find_last_not_of()
Find non-matching character in string from the end
stringstream (string to int)
stringstream ss;
ss << x;
ss >> s;
Number Theory
●
●
Access every integer digits: temp=n%10;
Modulo of negative number: #define mod(x,m) ((x%m)+m)%m;
Prime number under 100 (there are 25 numbers)
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
If prime number
bool prime(int n)
{
if (n<2) return false;
if (n<=3) return true;
if (!(n%2) || !(n%3)) return false;
for (int i=5;i*i<=n;i+=6)
if (!(n%i) || !(n%(i+2))) return false;
return true;
}
Prime factorization
// smallest prime factor of a number.
function factor(int n)
{
int a;
if (n%2==0)
return 2;
for (a=3;a<=sqrt(n);a++++)
{
if (n%a==0)
return a;
}
return n;
}
// complete factorization
int r;
while (n>1)
{
r = factor(n);
printf("%d", r);
n /= r;
}
Greatest common divisor — GCD
int gcd(int a, int b)
{
if (b==0) return a;
else return gcd(b, a%b);
}
Least common multiple — LCM
int lcm(int a, int b)
{
return a*b/gcd(a,b);
}
Leap year
bool isLeap(int n)
{
if (n%100==0)
if (n%400==0) return true;
else return false;
if (n%4==0) return true;
else return false;
}
Factorial mod
//n! mod p
int factmod (int n, int p) {
long long res = 1;
while (n > 1) {
res = (res * powmod (p-1, n/p, p)) % p;
for (int i=2; i<=n%p; ++i)
res=(res*i) %p;
n /= p;
}
return int (res % p);
}
●
●
●
●
●
ceil(), floor(), round()
১. 1+2+3+4+……+ n = [n(n+1)/2]
12+22 + 32+……+ n2= {n(n+1)(2n+1)}/6
1^3 + 2^3 + 3^3+……+n^3= n^2/4(n+1)^2
Generate combinations
// n>=m, choose M numbers from 1 to N.
void combination(int n, int m)
{
if (n<m) return ;
int a[50]= {0};
int k=0;
for (int i=1; i<=m; i++) a[i]=i;
while (true)
{
for (int i=1; i<=m; i++)
cout << a[i] << " ";
cout << endl;
k=m;
while ((k>0) && (n-a[k]==m-k)) k--;
if (k==0) break;
a[k]++;
for (int i=k+1; i<=m; i++)a[i]=a[i-1]+1;
}
}
All pairs
// pairs from the array
void printPairs(int arr[], int n)
{
// Nested loop for all possible pairs
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << "(" << arr[i] << ", " << arr[j] << ")" << ", ";
}
}
}
Permutations
void permute(string str)
{
sort(str.begin(), str.end());
do{
cout << str << endl;
} while (next_permutation(str.begin(), str.end()));
}
Dynamic Programming
0/1 Knapsack problems
#include<iostream>
using namespace std;
int f[1000]= {0};
int n=0, m=0;
int main(void)
{
cin >> n >> m;
for (int i=1; i<=n; i++)
{
int price=0, value=0;
cin >> price >> value;
for (int j=m; j>=price; j--)
if (f[j-price]+value>f[j])
f[j]=f[j-price]+value;
}
cout << f[m] << endl;
return 0;
}
Complete Knapsack problems
#include<iostream>
using namespace std;
int f[1000]= {0};
int n=0, m=0;
int main(void)
{
cin >> n >> m;
for (int i=1; i<=n; i++)
{
int price=0, value=0;
cin >> price >> value;
for (int j=price; j<=m; j++)
if (f[j-price]+value>f[j])
f[j]=f[j-price]+value;
}
cout << f[m] << endl;
return 0;
}
Longest common subsequence (LCS)
int dp[1001][1001];
int lcs(const string &s, const string &t)
{
int m = s.size(), n = t.size();
if (m == 0 || n == 0) return 0;
for (int i=0; i<=m; ++i)
dp[i][0] = 0;
for (int j=1; j<=n; ++j)
dp[0][j] = 0;
for (int i=0; i<m; ++i)
for (int j=0; j<n; ++j)
if (s[i] == t[j])
dp[i+1][j+1] = dp[i][j]+1;
else
dp[i+1][j+1] = max(dp[i+1][j], dp[i][j+1]);
return dp[m][n];
}
Palindromic permutations
#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
// Function to find all palindromic permutations of a given string
void printPalindromicPermutations(string str)
{
// base case
if (str.size() == 0) {
return;
}
// store frequency of each character of a string in a map
unordered_map<char, int> freq;
for (char ch: str) {
freq[ch]++;
}
int odd = 0;
string mid;
string left, right;
// iterate through the map
for (auto itr: freq)
{
// stores odd character's count
// stores odd character
// stores left and right-half
char ch = itr.first;
int c = itr.second;
// current character
// character count
if ((c
{
//
//
if
// if the count of the current character is odd
& 1))
if more than one odd character is present in the string,
palindromic permutations are not possible
(++odd > 1) {
return;
}
c = c - 1;
mid = itr.first;
// make count even or zero
// update mid
}
// append `c/2` characters to the left-half
// (other `c/2` characters will go in the right-half)
c = c/2;
while (c--) {
left = left + ch;
// update left
}
}
// sort left-half to generate permutations in lexicographical order
// no need to sort if we use `std::map` as keys are already sorted
sort(left.begin(), left.end());
while (1)
{
// the right-half will be the reverse of the left-half
right = left;
reverse(right.begin(), right.end());
// print left-half, middle character (if any), and right-half
cout << (left + mid + right) << endl;
// find the next lexicographically greater permutation
if (!next_permutation(left.begin(), left.end())) {
break;
}
}
// Note that we can also sort in reverse order and use `std::prev_permutation`
}
int main()
{
string str = "xyxzwxxyz";
printPalindromicPermutations(str);
return 0;
}
Merge Sort
#include<stdio.h>
int main()
{
mergeSort(arr, 0, n-1);
}
void mergeSort(int arr[], int l, int h)
{
if(l < h)
{
int m;
m = (l + h) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, h);
mergeArray(arr, l, m, h);
}
}
void mergeArray(int arr[], int l, int m, int h)
{
int i, j, k, a = m-l+1, b = h-m;
int temp1[a], temp2[b];
for(i=0;
temp1[i]
for(j=0;
temp2[j]
i<a; i++)
= arr[l+i];
j<b; j++)
= arr[m+1+j];
i=0, j=0, k=l;
while(i<a && j<b)
{
if(temp1[i] <= temp2[j])
{
arr[k] = temp1[i];
i++;
}
else
{
arr[k] = temp2[j];
j++;
}
k++;
}
while(i<a)
{
arr[k] = temp1[i];
i++;
k++;
}
while(j<b)
{
arr[k] = temp2[j];
j++;
k++;
}
}
Download