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

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 datas...

NT Part 2: Generating Primes, Prime Test, Prime Factorization

  Generating primes fast is very important in some problems. Let's cut to the chase and introduce Eratosthenes's Sieve. The main idea is the following. Suppose we want to find all primes between 2 and 50. Iterate from 2 to 50. We start with 2. Since it is not checked, it is a prime number. Now check all numbers that are multiple of    except  2. Now we move on, to number 3. It's not checked, so it is a prime number. Now check all numbers that are multiple of  ,   except  3. Now move on to 4. We see that this is checked - this is a multiple of 2! So 4 is not a prime. We continue doing this. Here's the implementation. #include <stdio.h> int primechk [ 21000 ] ;   void preprocess ( void ) { int i, j ; for ( i = 2 ; i <= 20000 ; i ++ ) { primechk [ i ] = 1 ; } for ( i = 2 ; i <= 20000 ; i ++ ) { if ( primechk [ i ] == 1 ) { for ( j = 2 ; i * j <= 20000...

NT Part 6: Sieve of Eratosthenes(Details)

  About 2300 years ago from today, famous Greek mathematician Euclid proved that there are an infinite number of prime numbers. Since then people have been searching for these prime numbers. In 1849, one of the greatest mathematician of all time, Carl Fredrick Gauss, had identified almost all of the prime numbers within the first 3 hundred thousand whole numbers. In the age of computers, we can find large prime numbers in the blink of an eye. But to do that, we need to know a bit of programming and a 2000 year old algorithm. By the end of this tutorial, you will be able to figure out a solution on your own to Gauss’s problem. What is a Prime Number? A prime number is an integer number that is divisible by 1 and the number itself only. For example, 7 is divisible by 1 and 7 only. But 6 is not a prime number because 6 is be divisible by 2 and 3 as well. It is worth mentioning that 1 itself is not a prime number. Now if you are asked to determine if a number is a prime number, you can...