3 min read

C++ Tricks to Turn You Into a Code Ninja

Master C++ with practical tricks and tips for writing smarter, faster, and more efficient code

C++ is powerful, but mastering it takes more than just knowing syntax. Here’s a collection of practical tricks and tips to help you code smarter, faster, and like a true C++ ninja.

1. String Tricks 📝

C++ strings are more than just std::string. You can do all sorts of cool things:

string s = "Hello World Interview";  
  
// Find substring  
if (s.find("World") != string::npos)  
    cout << "Found 'World'\\n";  
// Last occurrence  
cout << "Last 'l' at: " << s.rfind('l') << "\\n";  
// Substring  
cout << "Substring: " << s.substr(6, 5) << "\\n";  
// Split string by space  
vector<string> split(const string &s, char delim) {  
    vector<string> res;  
    string token;  
    stringstream ss(s);  
    while (getline(ss, token, delim))  
        res.push\_back(token);  
    return res;  
}  
auto words = split(s, ' ');

Other ninja moves:

  • Convert case: transform(s.begin(), s.end(), s.begin(), ::tolower);
  • Reverse string: reverse(s.begin(), s.end());
  • Check palindrome: bool isPal = equal(p.begin(), p.begin()+p.size()/2, p.rbegin());
  • String ↔ Number: stoi(“123”) or to_string(456)

2. Vector & Algorithm Tricks 🔥

Vectors + STL algorithms = ultimate ninja combo:

vector<int> v = {5, 1, 4, 2, 3, 2, 4, -1, -3};  
  
// Sort ascending  
sort(v.begin(), v.end());  
  
// Remove duplicates  
v.erase(unique(v.begin(), v.end()), v.end());  
  
// Remove negatives  
v.erase(remove\_if(v.begin(), v.end(), \[\](int x){ return x < 0; }), v.end());  
  
// Max / Min  
int mx = \*max\_element(v.begin(), v.end());  
int mn = \*min\_element(v.begin(), v.end());  
  
// Count even numbers  
int evenCount = count\_if(v.begin(), v.end(), \[\](int x){ return x % 2 == 0; });  
  
// Prefix sum  
vector<int> pref = v;  
partial\_sum(pref.begin(), pref.end(), pref.begin());

Other ninja moves: rotate(), nth_element(), binary_search(), all_of(), any_of(), accumulate().

3. Lower / Upper Bound 🎯

Quick way to count occurrences:

vector<int> freqTest = {1,2,2,2,3,4};  
int x = 2;  
int freq = upper\_bound(freqTest.begin(), freqTest.end(), x)  
         - lower\_bound(freqTest.begin(), freqTest.end(), x);

4. Maps, Unordered Maps & Sets 🗂️

STL containers are your ninja toolkit:

unordered\_map<int,int> um;  
for(int x : freqTest) um\[x\]++;  
  
map<string,int> mp;  
mp\["apple"\]++;  
if(mp.count("apple")) cout << "apple exists\\n";  
set<int> st = {1,2,3,4,5};  
for(auto it = st.begin(); it != st.end();) {  
    if(\*it % 2 == 0) it = st.erase(it);  
    else ++it;  
}

5. Pairs & Tuples 🔗

Sorting pairs & comparing tuples made easy:

vector<pair<int,int>> vp = {{1,3},{2,1},{3,2}};  
sort(vp.begin(), vp.end(), \[\](auto &a, auto &b){ return a.second < b.second; });  
  
int a=1,b=2,c=3,x1=1,y1=2,z1=4;  
bool cmpTuple = tie(a,b,c) < tie(x1,y1,z1);

6. Priority Queue (Heap) ⚡

priority\_queue<int> maxHeap; // default max heap  
priority\_queue<int, vector<int>, greater<int>> minHeap; // min heap  
  
for(int x : {5,1,3,4}) minHeap.push(x);  
cout << "MinHeapTop=" << minHeap.top() << "\\n";

7. Custom Struct Sorting 🏗️

Sort complex data easily with custom comparators:

struct Person { string name; int age; };  
bool ageCmp(const Person &a, const Person &b) { return a.age < b.age; }  
  
vector<Person> people = {{"Alice",25}, {"Bob",20}, {"Charlie",30}};  
sort(people.begin(), people.end(), ageCmp);

8. Bit Manipulation Ninja Moves 🧮

int n = 29; // 11101  
int setBits = \_\_builtin\_popcount(n);  
int leadingZeros = \_\_builtin\_clz(n);  
int trailingZeros = \_\_builtin\_ctz(n);  
  
bool isPowerOfTwo = (n & (n - 1)) == 0;  
int lowestBit = n & -n;  
n = n & (n - 1); // turn off lowest set bit

9. Min / Max in One Shot 🏆

auto \[mini, maxi\] = minmax(10, 20);

Master these tricks, and your C++ skills will level up like a true coding ninja! 🥷

Related Articles