Skip to content

Code Golf — STL Power Demonstrations

Một câu lệnh STL có thể thay thế 10+ dòng code loops thủ công. Học cách viết code ngắn gọn và expressive.

Example 1: Sum of Squares

Manual Loop (8 lines)

cpp
int sumOfSquares(const std::vector<int>& v) {
    int sum = 0;
    for (size_t i = 0; i < v.size(); ++i) {
        int squared = v[i] * v[i];
        sum += squared;
    }
    return sum;
}

STL One-liner

cpp
int sumOfSquares(const std::vector<int>& v) {
    return std::accumulate(v.begin(), v.end(), 0, 
        [](int acc, int x) { return acc + x * x; });
}

Even Shorter với transform_reduce (C++17)

cpp
int sumOfSquares(const std::vector<int>& v) {
    return std::transform_reduce(v.begin(), v.end(), 0, 
        std::plus<>(), [](int x) { return x * x; });
}

Example 2: Count Words Longer Than N

Manual Loop (9 lines)

cpp
int countLongWords(const std::vector<std::string>& words, size_t n) {
    int count = 0;
    for (size_t i = 0; i < words.size(); ++i) {
        if (words[i].length() > n) {
            count++;
        }
    }
    return count;
}

STL One-liner

cpp
int countLongWords(const std::vector<std::string>& words, size_t n) {
    return std::count_if(words.begin(), words.end(),
        [n](const std::string& s) { return s.length() > n; });
}

Example 3: Find Maximum Element

Manual Loop (10 lines)

cpp
int findMax(const std::vector<int>& v) {
    if (v.empty()) throw std::runtime_error("Empty vector");
    
    int maxVal = v[0];
    for (size_t i = 1; i < v.size(); ++i) {
        if (v[i] > maxVal) {
            maxVal = v[i];
        }
    }
    return maxVal;
}

STL One-liner

cpp
int findMax(const std::vector<int>& v) {
    return *std::max_element(v.begin(), v.end());
}

Example 4: Reverse and Sort

Manual (15+ lines)

cpp
void reverseSort(std::vector<int>& v) {
    // Manual reverse
    int left = 0;
    int right = v.size() - 1;
    while (left < right) {
        int temp = v[left];
        v[left] = v[right];
        v[right] = temp;
        left++;
        right--;
    }
    
    // Manual bubble sort
    for (size_t i = 0; i < v.size(); ++i) {
        for (size_t j = 0; j < v.size() - i - 1; ++j) {
            if (v[j] > v[j + 1]) {
                int temp = v[j];
                v[j] = v[j + 1];
                v[j + 1] = temp;
            }
        }
    }
}

STL Two-liner

cpp
void reverseSort(std::vector<int>& v) {
    std::reverse(v.begin(), v.end());
    std::sort(v.begin(), v.end());
}

Example 5: Remove Duplicates (Sorted)

Manual Loop (12 lines)

cpp
std::vector<int> removeDuplicates(std::vector<int> v) {
    std::sort(v.begin(), v.end());  // Assume sorted
    
    std::vector<int> result;
    for (size_t i = 0; i < v.size(); ++i) {
        if (i == 0 || v[i] != v[i - 1]) {
            result.push_back(v[i]);
        }
    }
    return result;
}

STL (Erase-Remove Idiom)

cpp
std::vector<int> removeDuplicates(std::vector<int> v) {
    std::sort(v.begin(), v.end());
    v.erase(std::unique(v.begin(), v.end()), v.end());
    return v;
}

Example 6: Check All Positive

Manual Loop (7 lines)

cpp
bool allPositive(const std::vector<int>& v) {
    for (size_t i = 0; i < v.size(); ++i) {
        if (v[i] <= 0) {
            return false;
        }
    }
    return true;
}

STL One-liner

cpp
bool allPositive(const std::vector<int>& v) {
    return std::all_of(v.begin(), v.end(), [](int x) { return x > 0; });
}

Example 7: String to Upper Case

Manual Loop (6 lines)

cpp
std::string toUpper(std::string s) {
    for (size_t i = 0; i < s.length(); ++i) {
        s[i] = std::toupper(s[i]);
    }
    return s;
}

STL One-liner

cpp
std::string toUpper(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
    return s;
}

Example 8: Generate Range [1..N]

Manual Loop (5 lines)

cpp
std::vector<int> range(int n) {
    std::vector<int> result;
    for (int i = 1; i <= n; ++i) {
        result.push_back(i);
    }
    return result;
}

STL Two-liner

cpp
std::vector<int> range(int n) {
    std::vector<int> result(n);
    std::iota(result.begin(), result.end(), 1);
    return result;
}

Example 9: Partition Evens/Odds

Manual (10+ lines)

cpp
std::pair<std::vector<int>, std::vector<int>> 
partitionEvenOdd(const std::vector<int>& v) {
    std::vector<int> evens, odds;
    for (size_t i = 0; i < v.size(); ++i) {
        if (v[i] % 2 == 0) {
            evens.push_back(v[i]);
        } else {
            odds.push_back(v[i]);
        }
    }
    return {evens, odds};
}

STL với partition_copy

cpp
std::pair<std::vector<int>, std::vector<int>> 
partitionEvenOdd(const std::vector<int>& v) {
    std::vector<int> evens, odds;
    std::partition_copy(v.begin(), v.end(),
        std::back_inserter(evens),
        std::back_inserter(odds),
        [](int x) { return x % 2 == 0; });
    return {evens, odds};
}

Example 10: Join Strings with Delimiter

Manual Loop (10 lines)

cpp
std::string join(const std::vector<std::string>& v, const std::string& delim) {
    if (v.empty()) return "";
    
    std::string result = v[0];
    for (size_t i = 1; i < v.size(); ++i) {
        result += delim;
        result += v[i];
    }
    return result;
}

STL với accumulate

cpp
std::string join(const std::vector<std::string>& v, const std::string& delim) {
    if (v.empty()) return "";
    return std::accumulate(std::next(v.begin()), v.end(), v[0],
        [&delim](const std::string& a, const std::string& b) {
            return a + delim + b;
        });
}

Comparison Table

TaskManual LinesSTL LinesReduction
Sum of squares8275%
Count matching9278%
Find max10190%
Reverse + sort15+287%
Remove duplicates12375%
All positive7186%
To upper case6267%
Generate range5260%

Average reduction: ~77% fewer lines!


🎓 Professor Tom's Advice

📌 STL Best Practices

  1. Learn the algorithms — Có hơn 100 algorithms, nhưng chỉ cần ~20 cho 90% use cases
  2. Think declaratively — WHAT not HOW
  3. Compose operations — Chain algorithms thay vì nested loops
  4. Benchmark — STL thường nhanh hơn hand-written code
  5. Read the docscppreference.com

📚 Tổng kết

The 10 Most Useful Algorithms

#AlgorithmUse Case
1std::sortSorting
2std::find / find_ifSearching
3std::count / count_ifCounting
4std::accumulateSumming/Reducing
5std::transformMapping
6std::copy / copy_ifFiltering
7std::max_element / min_elementFinding extremes
8std::all_of / any_of / none_ofBoolean checks
9std::uniqueRemoving duplicates
10std::reverseReversing

🎉 Hoàn thành STL Part 2: Algorithms!

Bạn đã nắm vững:

  • ✅ Lambda expressions extensive
  • ✅ Custom comparators
  • ✅ Searching algorithms
  • ✅ Transform & Reduce
  • ✅ Code golf — STL power

Tiếp theo: Part 5 — Modern C++ (Smart Pointers, Move Semantics)