Skip to main content

STL-3

 

Most coders use C++ language for competitive programming. It is used widely because of its reliability, faster execution, short snippets, etc. Easy availability of the tutorials in c++ makes it more adaptive by coders. C++ STL is the backbone of programming. The inbuilt functions reduce a code snippet to even a single line sometimes.

Example: To sort an array, no need to write the whole algorithms of sorting. A function does all the magic here which is known as “sort” function.

Now let’s look at some interesting facts about STL and c++ programming.

> GCD function
GCD of two numbers is found with __gcd(a,b) where a and b are two numbers. No need to write
the Euclidean algorithm. The function returns an integer, the GCD.
Note – This function works only in GCC.
Example-

include<bits/stdc++.h>

using namespace std;
int main()
{
cout << __gcd(45,15); // outputs 15 as GCD
return 0;
}

Sometimes it is messy to convert an int to a string and vice versa which at times gives errors. Here are two functions that make life quite easy.

> to_string function
To convert an integer to a string, this function is used.
Example –
string str = to_string(12345); // str is a string with value as “12345”

include<bits/stdc++.h>

using namespace std;
int main()
{
int x = 12345′
string str = to_string(x); // Outputs string “12345”
return 0;
}

> stoi function
To convert string to an integer, this function is used.
Example –
int x = stoi(“2665”); // x is now an int with value 2665

include<bits/stdc++.h>

using namespace std;
int main()
{
string str = ‘”2665″;
int x = stoi(str);
cout << x ; // x is now a int with value 2665
return 0;

}

> facts about sets in STL
By default a set stores values in non-decreasing order.
To convert into non-increasing order syntax is:
set<int, greater> s;

>memset function
By using this function, the array elements initialised to either 0 or 1 but not other values.
Example –

include<iostream>

using namespace std;
int main()
{
int arr[5];
memset(arr, 0, sizeof(arr)); // First argument as array name, Second as the 0 or 1 , Third as the
size of array.
memset(arr, -1, sizeof(arr));
// Invalid
memset(arr, 5, sizeof(arr)); // It will store garbage value instead of 5
return 0;
}

> New method of assigning values to pairs
Generally, the make_pair function used to assign the values to a pair.
{} are used to save time.
Example –
pair<int, int> p = make_pair(3,4); // Method 1
pair<int, int> p= {3,4}; // Method 2
Even a more complex pair can be assigned using method 2
pair<char, <pair, pair>> p = { ‘c’, {2,5} };

NOTE
Furthermore, a tuple can store different type of values.
tuple t = {1, ‘a’, 3, 4};

> Static variable = 0.
Every static variable is assigned to 0 by default.
Example –

include<bits/stdc++.h>

using namespace std;
static int x;
int main()
{
cout << x; // Outputs 0
return 0;
}

> Count number of set bits in a number
__builtinpopcount() function used to find the number of set bits. It works only in GCC
compilers.
Example –

include<bits/stdc++.h>

using namespace std;
int main()
{
int x = 5;
cout << __builtinpopcount(x); /* outputs 2 as 5 is represented as 101 in binary number system */
return 0;
}
Note
__builtinpopcountll() is used for long long integers.

> Facts about data types in c++
 If no data type assigned to a variable, it automatically gets converted to int type.
Example –

include<iostream>

using namespace std;
int main()
{
signed a;
cout << sizeof(a); // outputs 4 as size of int
return 0;

}
 The default modifier of char and int data type is signed.
Example-

include<iostream>

using namespace std;
int main()
{
int x = -1;
char y = -2;
cout << x << ” ” << y; // Outputs the original value of x
// AND y
return 0;
}
 No modifiers can be used with float data types.
Example-

include<iostream>

using namespace std;
int main()
{
signed float x ;
short float b ;
return 0 ;
}
The above program gives compile-time errors-
” [Error] both ‘signed’ and ‘float’ in declaration specifiers
[Error] both ‘short’ and ‘float’ in declaration specifiers “

 The only long specifier can be used with a double data type. Any other specifier will result in a compile-time error.
Example-

include<iostream>

using namespace std;
int main()
{
long double x ; // Works
short double y; // Error as above
return 0;
}

> Default arguments acceptance
Default arguments must be written in the function declaration, not definition otherwise it will
give compile errors.

Example-

include<iostream>

using namespace std;
void deffunc( int a=1, int b=2, int c=3); // Error
int main()
{
deffunc();

return 0;
}
void deffunc( int a=1, int b=2, int c=3)
{
cout << a << ” ” << b << ” ” << c;
}
The following program corrected by eliminating the values in the function definition.

include<iostream>

using namespace std;
void deffunc( int a=1, int b=2, int c=3); // Error
int main()
{
deffunc();
return 0;
}
void deffunc( int a, int b, int c)
{
cout << a << ” ” << b << ” ” << c;
}

Note

include <iostream>

using namespace std;
// something looks missing

void init(int =8, int =9, int =13);
int main()
{
init();
return 0;
}
void init(int a, int b, int c)
{
cout << a << ‘ ‘ << b << ‘ ‘ << c;
}

The above function prototype looks like it has an error but it is correct. Variable names can be skipped in default arguments.

  1. Bitset is like a string: Bitset is a container of bits ( only 0 and 1 are valid ). You can create a bitset with any set of bits specified by a start index value of the bitset and the number of elements that are considered i.e. you can create a bitset with two elements starting from index 1 of the bitset and append it to the end of the bitset.

Example

include <bitset>

include <string>

include <iostream>

int main() {
std::string bit_string = “10010110”;
std::bitset<8> b1(bit_string, 1 , 4);

std::cout << b1 << ‘\n’ ;
return 0;
}
Output
00000010

  1. Constructing a Bitset from a string: If you have a string that has only two types of values that are used while creating. You can convert this string into a bitset that considers values as there respective 0/1 representation. Let’s take an example to understand this concept better, we have a string ‘xyxxyyx’, from this we can create a bitset with the same length as the array considering x = 0 and y= 1. The bitset created as 0100110. There is a constructor defined in the library to perform this task − bitset(str, offset, size, zeroVal, oneVal) ; This is a constructor that is defined to create a bitset. Let’s dig in deep into the constructor and learn what each parameter of the constructor conveys.
    str − The string that is to be considered for creating the bitset.
    offSet − string index of the string.
    size − Size of the bitset that is to be created.
    zeroVal − The value of the string that will be considered 0
    oneVal − The value of the string that will be considered 1]
    Example

include <bitset>

include <string>

include <iostream>

using namespace std;
int main() {

string bitstr = “xyxxyyyx”;
bitset<8> bits(bitstr, 0, bitstr.size(), ‘x’, ‘y’);
cout <<“The bitset is : “<< bits << ‘\n’;
}
Output
The bitset is: 01001110

  1. Convert bitset to string: In bitset, there is a function to convert a bitset to a string. The
    function to_string() is used to store the values of the bitset into a string. The length of the string
    is the same as the length of the bitset. The order storing the elements of the bit set into the string is the same as the bitset order i.e. the first element of the bitset first element of the string. String conversion of 01010100 is “01010100”. You can replace 0 and 1 by any letter by specifying in the parameter list of the method. It is just the reverse of what we learned while construction of bitset.
    Example

include <iostream>

include <bitset>

using namespace std;
int main() {
bitset<8> b(19);
cout<<“The value of the bitset is : “<<b<<endl;
cout<<“The string conversion of the bitset is : “<<b.to_string()<<endl;
cout<<“The string conversion by replacing 0 with T and 1 with P is : “;
cout<< b.to_string(‘T’, ‘P’)<<endl;
}
Output
The value of bitset is: 00010011

The string conversion of bitset is 00010011 string conversion by replacing 0 with T and 1 with P is: TTTPTTPP.

Comments

Popular posts from this blog

Breaking The Summation Formula (Part 1)

 Q. f ( n ) =  - 1 + 2 - 3 + .. + ( - 1) n n .  Given n, find out f(n) Approach(1)- Bruteforce: 1. Calculation sum=n*(n+1)/2 2. loop[i=1,i=n : i+=2] odd+=i 3.ans=sum-2*odd Code: #include < bits / stdc ++. h > using namespace std ; int main (){   long long x ; cin >> x ; long long p =( x *( x + 1 ))/ 2 ; long long bad = 0 ; for ( long long i = 1 ; i <= x ; i += 2 ) bad += i ; cout << p - 2 * bad << endl ; } Approach(2)-Greedy: Basic: s=1+2+3+4+....+n Formula: sum=n*(n+1)/2= (n/2) + (n+1).2

Big O Notation — Time & Space Complexity in Ruby!

  Big O Cheat Sheet In this post, we will look at the Big O Notation both time and space complexity! For all our examples we will be using Ruby. What is Big O Notation? Big O notation is just a fancy way of describing how your code’s performance depends on the amount of data its processing. It allows us to calculate the worst possible runtime of an algorithm, or how long it takes the algorithm to complete. In other words, it informs us of how much it will slow down based on the input size. It’s usually talked about in two ways the  time complexity ( how long an algorithm takes )and  space complexity ( how much space an algorithm uses ) Let me put this graph here we can refer to it as we go on, it’s a graph showing the complexities compare against each other. Big O complexity chart Time Complexity Before we get try wrapping our heads around the different big O notations here is a nice table that I am borrowing to show how speed will slow down based on the size of the dataset. I found th

Game Theory with examples

Game Theory with examples Introduction In this article I will be covering problems related to two players game in which it is assumed that both players play optimally and we have to find out the winner of the game. First we will look at the  basic   division of positions to winning and losing . Then we will see the  Game of Nim  and then see how it will be used to solve the  Composite games . Basic Division of positions to winning and losing Problem Statement:  Consider a simple game played by two players A and B . There are n stones on the table. Each player can pick 1 , 2 or 5 stones in each turn. Both players pick the stones alternately until the total number of stones left on the table is 0. The player unable to make the move will lose. Assuming that both the players play optimally, output the winner of the game. Solution:  As you can see positions 1 , 2 and 5 are winning positions since the player can pick up all the stones and other player will not be able to make a move . 0 is a