[
  {
    "path": "README.md",
    "content": "# C++ STL Quick Help\nIt contains C++ STLs usage and quick help with easy to understand comments and examples (copy+paste to use).\nI learned these while solving different kinds of Leetcode Questions.  \nI will be using \"int, string etc\" for ease and not complex entities like pairs, structs etc 😉. You can replace it with any data structure\nIf you are confused with the syntax or description, see the example. I am sure that will clear things BECAUSE I have specifically chosen  \n:mag_right: \"EASY + IMPORTANT + MOST USED\" examples.\nLast but not least, I have added Leetcode Qns also which can be easily solved using STLs\n\n### :memo:Different ways of using priority_queue (i.e. heap) :mount_fuji:\n\n- Default declarations\n```c++\npriority_queue<int> pq;                            //creates max-heap\npriority_queue<int, vector<int>> pq;               //creates max-heap\n```\n<br>\n\n- writing comparator function for priority_queue\n```c++\n1. Using in-built comparator provided by C++ : \n\npriority_queue<int, vector<int>, greater<int>> pq;  //creates min-heap\npriority_queue< pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > pq; //min_heap of pairs\npriority_queue< pair<int, int>, vector<pair<int, int>>, greater<> > pq;               //min_heap of pairs\n```\n```c++\n2. Using user defined comparator as a structure\n\nstruct comp {\n    bool operator()(int &a, int &b) {\n        return a<b; //max-heap\n        return a>b; //min-heap\n    }\n};\n\npriority_queue<int, vector<int>, comp> pq;  //usage\n```\n\n```c++\n3. Using user defined comparator as a function\n\nstatic bool comp(int &a, int &b) {\n    return a<b; //max-heap\n    return a>b; //min-heap\n}\n\npriority_queue<int, vector<int>, function<bool(int&, int&)> > pq(comp);   //usage\n```\n```c++\n4. Using lambda function\n\nauto comp = [](int &a, int &b) {\n    return a<b; //max-heap\n    return a>b; //min-heap \n};\n\npriority_queue<int, vector<int>, decltype(comp) > pq(comp);   //usage\n\nNOTE :\nYou can receive parameters inside [] as well i.e. auto comp = [some_parameters]\nEx : You want to access a map inside this lambda function\nunordered_map<int, int> mp;\n\nauto comp = [&mp](int &a, int &b) {\n    return mp[a] < mp[b]; //etc.\n};\n\n```\n\n### :memo: When and why to use std::move() :arrow_left:\n```c++\n/*\n    To efficiently transfer the resources from source to target.\n    By efficient, I mean no usage of extra space and time for creating copy.\n*/\nExamples :\n    string source = \"MIK\";\n    string target = \"\";\n    target = std::move(source);\n    cout << \" source = \" << source << endl;\n    cout << \"target = \"  << target << endl;\n    /*\n        output :\n        source = \n        target = \"MIK\"\n    */\n    \n    vector<string> v;\n    string str = \"example\";\n    v.push_back(std::move(str));\n    /*\n    After this, str becomes empty i.e. \"\"\n    And while moving str inside v, no extra copy of str was done implicitly.\n    */\n\n    vector<int> temp{1, 2, 3};\n    vector<vector<int>> result;\n    result.push_back(std::move(temp));\n    /*\n    This allows no copy of \"temp\" being created.\n    It ensures that the contents of \"temp\"\n    will be moved into the \"result\".  This is less\n    expensive, also means temp will now be empty.\n    */\n```\n\n### :memo: std::accumulate(begin_iterator, end_iterator, initial_sum) :heavy_plus_sign:\n```c++\nint sum = 0;\nvector<int> nums{1, 3, 2, 5};\nsum = accumulate(begin(nums), end(nums), 0);\n\ncout << sum; //11\n\nBenefit : You didn't have to write for loop to find the sum\n```\n\n### :memo: std::accumulate(begin_iterator, end_iterator, initial_sum, lambda) :heavy_plus_sign:\n```c++\nlambda : Binary operation taking an element of type <initial_sum> as first argument and an\n            element in the range as second, and which returns a value that can be assigned to type T.\n\nExample-1 : \n\nauto lambda = [&](int s, long n) {\n    return s + n*n; //sums the square of numbers\n    //You can call any other function inside as well\n};\n\nint sum = 0;\nvector<int> nums{1, 3, 2, 5};\nsum = accumulate(begin(nums), end(nums), 0, lambda);\n\ncout << sum; //39\n\nExample-2 : Handling 2-D matrix\n//Summming all elements row by row\nauto lambda = [&](int sum, vector<int> vec) {\n    sum = sum + accumulate(begin(vec), end(vec), 0);\n    return sum;\n};\n\nint result =  accumulate(matrix.begin(), matrix.end(), 0, lambda);\n\n\nBeautiful example and usage :\nLeetcode-1577 (My Approach - https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/1305961/C%2B-(A-very-simple-Two-Sum-like-approach)\n\nLeetcode-1572 (My Approach - https://leetcode.com/problems/matrix-diagonal-sum/discuss/3498479/Using-C%2B%2B-STL-%3A-accumulate)\n\n```\n\n### :memo: min_element(begin_iterator, end_iterator), max_element(begin_iterator, end_iterator), minmax_element(begin_iterator, end_iterator) :astonished:\n```c++\nvector<int> nums{1, 3, 2, 5};\n\nint minimumValue = *min_element(begin(nums), end(nums)); //1\nint maximumValue = *max_element(begin(nums), end(nums)); //5\n                OR,\n        auto itr  = minmax_element(begin(nums), end(nums));\nint minimumValue  = *itr.first;  //remember, first is minimum  //1\nint maximumValue  = *itr.second; //remember, second is maximum //5\n\n\nBenefit : You didn't have to write for loop to find the max or min element\n```\n\n### :memo: upper_bound(), lower_bound() in sorted vector, ordered set, ordered map :outbox_tray:\n```c++\n\nFor vector:\nvector<int> vec{10,20,30,30,20,10,10,20};\nvector<int>::iterator up  = upper_bound(begin(vec), end(vec), 35);//returns iterator to first element \"greater\" than 35\nvector<int>::iterator low = lower_bound(begin(vec), end(vec), 35);//returns iterator to first element \"greater or equal\" to 35\ncout << \"upper_bound at position \" << (up - vec.begin()) << '\\n';\ncout << \"lower_bound at position \" << (low- vec.begin()) << '\\n';\n\nFor set:\nst.upper_bound(35); //returns iterator to first element \"greater\" than 35\nst.lower_bound(35); //returns iterator to first element \"greater or equal\" than 35\n\nFor map:\nmp.upper_bound(35); //returns iterator to first element \"greater\" than 35\nmp.lower_bound(35); //returns iterator to first element \"greater or equal\" than 35\n\nBenefit : You didn't have to write binary search (in case of vector),\nJAVA's tree_map equivalent in C++ (in case of map or set)\nThere are amazing applications or problems that can be solved using the above concepts.\nExample : My Calendar I (Leetcode - 729) -\n         You can find it in my interview_ds_algo repository as well B-)\n```\n\n### :memo: std::rotate 🌀\n```c++\nvector<int> vec{1, 2, 3, 4};\nint n = vec.size();\nint k = 2;\n\nrotate(vec.begin(), vec.begin()+k, vec.end());   //Left Rotate by K times\n\nrotate(vec.begin(), vec.begin()+n-k, vec.end()); //Right Rotate by K times\n\n```\n\n### :memo: To check if some rotation of string s can become string t🌀\n```c++\n\nstring s = \"abcde\";\nstring t = \"cdeab\";\n\ncout << (s.length() == t.length() && (s+s).find(t) != string::npos) << endl;\n\n```\n\n### :memo: std::next_permutation ➡️\n```c++\nIt gives the next lexicographically greater permutation.\nSo, if the container is already the greatest permutation (descending order), it returns nothing.\n\nvector<int> vec{1, 2, 3, 4};\n    \nif(next_permutation(begin(vec), end(vec)))\n    cout << \"Next permutation available\" << endl;\n\nfor(int &x : vec)\n    cout << x << \" \";\n    \n//Output : 1, 2, 4, 3\n\nAlso see : std::prev_permutation() - It gives just the previous lexicographically smaller permutation.\nBut I have never encountered any question where it's required till now. So you can skip it.\n    Leetcode - 31  : Next Permutation\n    etc.\n```\n\n\n### :memo: std::stringstream :fast_forward:\n```c++\nUsage:\n1) Converting string to number\n2) Count number of words in a string\n\nExample-1\n    string s = \"12345\";\n    stringstream ss(s);\n \n    // The object has the value 12345 and stream\n    // it to the integer x\n    int x = 0;\n    ss >> x;\n    cout << x;\n    \nExmaple-2\n    stringstream s(ss);\n    string word; // to store individual words\n  \n    int count = 0;\n    while (s >> word)\n        count++;\n    cout << count;\n    NOTE: It will tokenize words on the basis of ' ' (space by default) characters\nExample-3\n    It can be used very well to extract numbers from string.\n    string complex = \"1+1i\";\n    stringstream ss(complex);\n    char justToSkip;\n    int real, imag;\n    ss >> real >> justToSkip >> imag >> justToSkip;\n    cout << real << \", \" << imag; //output : 1, 1\n    \n    Other application on this STL :\n    Leetcode - 151  : Reverse Words in a String\n    Leetcode - 186  : Reverse Words in a String II\n    Leetcode - 557  : Reverse Words in a String III\n    Leetcode - 1108 : Defanging an IP Address\n    Leetcode - 1816 : Truncate Sentence\n    Leetcode - 884  : Uncommon Words from Two Sentences\n    Leetcode - 537  : Complex Number Multiplication (Example-3 above)\n    Leetcode - 165  : Compare Version Numbers\n    etc.\n```\n\n\n### :memo: std::transform(InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op) :robot:\n```c++\nApplies an operation sequentially to the elements of one (1) or\ntwo (2) ranges and stores the result in the range that begins at result.\nUage :\n1) Convert all letters of a string to lower case\n2) Convert all letters of a string to upper case\n\nExample : \n    string line = \"Hello world, this is MIK\";\n\n    transform(begin(line), end(line), begin(line), ::tolower);\n\n    cout << line << endl;\n\n    transform(begin(line), end(line), begin(line), ::toupper);\n\n    cout << line << endl;\n\n```\n\n### :memo: std::regex_replace :pager:\n```c++\nIt converts a regular expression given by user to desired expression given by user.\n\nExample : \n    Ex-1 - Remove all vowels from a string.\n    string s = \"mika\";\n    auto rgx = regex(\"[aeiouAEIOU]\");\n    cout << regex_replace(s, rgx, \"\");\n    \n    Ex-2 - Replace all '.' to \"[.]\"\n    string s = \"1.2.3.4\";\n    auto rgx = regex(\"\\\\.\");\n    regex_replace(s, rgx, \"[.]\");\n    \n    Note : You can write smart regex for achieving amazing replacements.\n    Qns on Leetcode:\n    Leetcode - 1108 : Defanging an IP Address\n    Leetcode - 1119 : Remove Vowels from a String\n    etc.\n```\n\n### :memo: std::count_if :1234:\n```c++\ncounts the number of elements satisfying a given condition (given by comparator function or lambda)\n\nExample : \n    vector<int> vec{1, 3, 2, 0, 5, 0};\n\n    auto lambda = [&](const auto& i) {\n        return i == 0;\n    };\n\n    cout << count_if(begin(vec), end(vec), lambda); //output : 2\n    \n    Note : You can write any kind of lambda/comparator functions for matching your required condition\n    Qns on Leetcode:\n    Leetcode - 1773 : Count Items Matching a Rule\n    etc.\n```\n\n### :memo: std::copy_if :1234:\n```c++\nCopies the elements to a container\nhow copy_if function works : in this function you have to pass four parameters \ncopy_if(begin iterator , end iterator , destination , condition)\n\t\t\t\n    eg :    vector<int> from_vec = {1,2,3,4,5,6,7,8,9,10};\n            vector<int> to_vec;\n            //here i want to copy all the number from from_vec vector to to_vec vector which are divisible by 2 .\n            \n            copy_if(from_vec.begin(), from_vec.end(), back_inserter(to_vec),[](int n){return n%2==0;});\n            \n            for(auto it : to_vec) \n                cout<<it<<\" \";\n            o/p : 2 4 6 8 10\nExample : \n    Note : You can write any kind of lambda/comparator functions for matching your required condition\n    Qns on Leetcode:\n    Leetcode - 1796 : Second Largest Digit in a String\n    etc.\n```\n\n\n### :memo: Writing lambda for upper_bound or lower_bound for vector<pair<int, string>> :1234:\n```c++\nExample-1 : \n        //Let's say you want upper_bound for a variable timestamp, take it in a pair (because it's a vector of pair)\n        pair<int, string> ref = make_pair(timestamp, \"\");\n            \n        auto lambda = [](const pair<int, string>& p1, const pair<int, string>& p2) {\n            return p1.first < p2.first;\n        };\n        \n        auto it = upper_bound(begin(my_vector), end(my_vector), ref, lambda);\n\t\nExample-2 : \n        //Let's say you want to find upper_bound of a value in a non-increasing vector.\n\tvector<int> vec{1, 0, -1, -2}\n\tint idx = upper_bound(begin(vec), end(vec), 0, greater<int>()) - begin(vec);\n\tOutput will be index of -1 (i.e. 2)\n\t\n\tQns on Leetcode:\n    \tLeetcode - 981 : Time Based Key-Value Store\n\tLeetcode - 744 : Find Smallest Letter Greater Than Target\n\tLeetcode - 1351 : Count Negative Numbers in a Sorted Matrix\n    \n```\n\n\n### :memo: Writing lambda for unordered_map to make life simple :1234:\n```c++\nExample : \n        //Let's say, you want to store different evaluate logic for different operator \"+\", \"-\", \"*\", \"/\"\n\tunordered_map<string, function<int (int, int) > > mp = {\n            { \"+\" , [] (int a, int b) { return a + b; } },\n            { \"-\" , [] (int a, int b) { return a - b; } },\n            { \"*\" , [] (int a, int b) { return a * b; } },\n            { \"/\" , [] (int a, int b) { return a / b; } }\n        };\n\t\n\t//Simply use it like below :-\n\tint result = mp[\"+\"](1, 2); //This will return 1+2 i.e. 3\n\t\n\tQns on Leetcode: 150\n\tLeetcode - : Evaluate Reverse Polish Notation\n    \n```\n\n\n\n\n### :memo: std::set_difference and std::back_inserter :1234:\n```c++\nset_difference -> Copies the elements from the sorted s1 which are not found in the sorted s2 to a container in sorted order\nback_inserter -> Can be used to add elements to the end of a container\nExample : \n        set<int> st1, st2;\n\tvector<int> v1;\n\t//Find difference in between set1 and set2 and put unique element of set1 in v1\n\tset_difference(begin(st1), end(st1), begin(st2), end(st2), back_inserter(v1));\n\t\n\tQns on Leetcode: \n\tLeetcode 2215 : Find the Difference of Two Arrays\n    \n```\n\n\n### :memo: std::hypot :triangular_ruler:\n```c++\nhypot -> Computes sqrt(x*x + y*y) (or sqrt(x*x + y*y + z*z) in C++17) safely, avoiding overflow/underflow.\n\nExample-1 : Compute hypotenuse of right triangle\n        double x = 3.0, y = 4.0;\n        double result = std::hypot(x, y);\n        cout << result; //5.0\n\nExample-2 : Distance between two points (x1, y1) and (x2, y2)\n        double x1 = 1, y1 = 2;\n        double x2 = 4, y2 = 6;\n        double dist = std::hypot(x2 - x1, y2 - y1);\n        cout << dist; //5.0\n\nExample-3 (C++17) : 3D Distance\n        double x = 1, y = 2, z = 2;\n        double dist3D = std::hypot(x, y, z);\n        cout << dist3D; //3.0\n\nBenefit :\n        - Numerically stable (avoids overflow/underflow)\n        - Cleaner than writing sqrt(x*x + y*y)\n        - Works with float, double, long double\n\nQns on Leetcode:\n        Leetcode 812 : Largest Triangly Area\n"
  }
]