Many people don't even realize how good C++ is until they come to know about it's Standard Template Library

This is the thread with some of the STL hacks that you should know

👇👇
1. __gcd(a, b)

The method to find the gcd of two numbers is __gcd(a, b)

(Note: There are TWO underscores before the function name)

👇👇
2. __builtin_popcount(a)

This method returns the number of 1s present in the binary notation of the number.

For eg : __builtin_popcount(4) = 1 (since 4b=100)

👇👇
3. __builtin_ctz(a)

This method returns the number of trailing zeros of a number a.

This is also convenient in cases where you want the least significant bit of a number.

eg. __builtin_ctz(16) = 4

👇👇
4. auto

auto for C++ is similar to the enhanced for loop of Java, except here we don’t need to even define the datatype of the iterator as it AUTOmatically gets defined

👇👇
5. accumulate(arr.begin(), arr.end(), init)

This method the sum of all elements For eg :

vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int sum = std::accumulate(v.begin(), v.end(), 0);

cout<<sum // will print 55

👇👇
6. iota(arr.begin(), arr.end(), val)

The final method on my list, is iota which populates an array/vector in increasing values starting from val

vector<int> a(10);
iota(a.begin(), a.end(), 2);

for(auto i:a)cout<<i<<" ";

// This outputs - 2 3 4 5 6 7 8 9 10 11
You can follow @apoorv__tyagi.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: