DEV Community

Rahul kumar
Rahul kumar

Posted on

Some tips for competitive programmers

Here I am going to present two methods that can be used for finding maximum among more that two numbers using max() and split a string around any delimiter.

Use max() for more than two numbers

max() is a c++ library function used to calculate maximum among it's arguments.

use

cout<<max(4,9);
// output : 9
Enter fullscreen mode Exit fullscreen mode

To calculate max among more than two numbers, we usually do this.

// calculate max of 4, 8  and 45
cout<<max(max(4,8),45);
// 45
Enter fullscreen mode Exit fullscreen mode

But, instead of complacting the code, we car write it like this

// calculate max of 4, 8  and 45
cout<<max({4,8,45});
// 45
Enter fullscreen mode Exit fullscreen mode

split a string around any delimiter

Suppose you have a string str

string str = "This, is, rahul";
Enter fullscreen mode Exit fullscreen mode

and you would like to remove the , from the string and return all the strings as an array of string

// should be
["this","is","rahul"];
Enter fullscreen mode Exit fullscreen mode

We can solve this problem using some techniques

#include<bits/stdc++.h>
using namespace std;
const vector<string> split(const string& s, const char& c)
{
    string buff{""};
    vector<string> v;

    for(auto n:s)
    {
        if(n != c) buff+=n; else
        if(n == c && buff != "") { v.push_back(buff); buff = ""; }
    }
    if(buff != "") v.push_back(buff);

    return v;
}

int main()
{
    string str{"the quick brown fox jumps over the lazy dog"};
    vector<string> v{split(str, ' ')};
    for(auto n:v) cout << n << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

The code speeks very well.

Let me know if this can be improved in any way.

Top comments (0)