C++ Tricks to Turn You Into a Code Ninja
Source: Dev.to
String Tricks
std::string s = "Hello World Interview";
// Find substring
if (s.find("World") != std::string::npos)
std::cout split(const std::string& s, char delim) {
std::vector res;
std::string token;
std::stringstream ss(s);
while (std::getline(ss, token, delim))
res.push_back(token);
return res;
}
auto words = split(s, ' ');
Other useful operations:
// Convert case
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
// Reverse string
std::reverse(s.begin(), s.end());
// Check palindrome
bool isPal = std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
// String ↔ Number
int n = std::stoi("123");
std::string str = std::to_string(456);
Vector and STL Algorithms
std::vector v = {5, 1, 4, 2, 3, 2, 4, -1, -3};
// Sort ascending
std::sort(v.begin(), v.end());
// Remove duplicates
v.erase(std::unique(v.begin(), v.end()), v.end());
// Remove negatives
v.erase(std::remove_if(v.begin(), v.end(),
[](int x){ return x pref = v;
std::partial_sum(pref.begin(), pref.end(), pref.begin());
Additional handy algorithms: std::rotate, std::nth_element, std::binary_search, std::all_of, std::any_of, std::accumulate.
Quick Count of Occurrences
std::vector freqTest = {1,2,2,2,3,4};
int x = 2;
int freq = std::upper_bound(freqTest.begin(), freqTest.end(), x) -
std::lower_bound(freqTest.begin(), freqTest.end(), x);
STL Containers as Ninja Toolkit
// Unordered map frequency counter
std::unordered_map um;
for (int x : freqTest) um[x]++;
// Ordered map example
std::map mp;
mp["apple"]++;
if (mp.count("apple")) std::cout st = {1,2,3,4,5};
for (auto it = st.begin(); it != st.end(); ) {
if (*it % 2 == 0) it = st.erase(it);
else ++it;
}
Sorting Pairs & Comparing Tuples
std::vector> vp = {{1,3},{2,1},{3,2}};
std::sort(vp.begin(), vp.end(),
[](const auto& a, const auto& b){ return a.second maxHeap; // default max‑heap
std::priority_queue, std::greater> minHeap; // min‑heap
for (int x : {5,1,3,4}) minHeap.push(x);
std::cout people = {{"Alice",25}, {"Bob",20}, {"Charlie",30}};
std::sort(people.begin(), people.end(), ageCmp);
Bit Manipulation Tricks
int n = 29; // binary 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
auto [mini, maxi] = std::minmax(10, 20);
Master these tricks, and your C++ skills will level up like a true coding ninja! 🥷