Skip to content
Laviyx Learn

Try

C++ STL Practice

Practise std::map, std::set, std::unordered_map, stacks, priority queues and the standard algorithms on real tasks.

Intermediate7 problemsUpdated

Review first: STL Overview, map, unordered_map and unordered_set, set, stack, queue and priority_queue, Algorithms, Iterators

  1. 1.Word frequency with map

    Intermediate

    Count the words in "red blue red green blue red" and print each word with its count, in alphabetical order.

    Show hint

    ++counts[word] creates an entry with 0 the first time, then increments it. A std::map keeps its keys sorted.

    Show solution
    C++
    #include <iostream>
    #include <map>
    #include <sstream>
    #include <string>
    
    int main() {
        std::istringstream in("red blue red green blue red");
        std::map<std::string, int> counts;
        std::string word;
        while (in >> word) {
            ++counts[word];
        }
        for (const auto& [w, n] : counts) {
            std::cout << w << ' ' << n << '\n';
        }
    }
    Output
    blue 2
    green 1
    red 3
  2. 2.Unique and sorted with set

    Intermediate

    From {7, 3, 7, 1, 3, 9, 1}, print the distinct values in ascending order, and the smallest and largest distinct value.

    Show hint

    Build a std::set from the vector's range. The smallest is *s.begin(), the largest *s.rbegin().

    Show solution
    C++
    #include <iostream>
    #include <set>
    #include <vector>
    
    int main() {
        std::vector<int> v = {7, 3, 7, 1, 3, 9, 1};
        std::set<int> s(v.begin(), v.end());
    
        for (int x : s) std::cout << x << ' ';
        std::cout << '\n' << *s.begin() << ' ' << *s.rbegin() << '\n';
    }
    Output
    1 3 7 9
    1 9
  3. 3.Two sum with unordered_map

    Intermediate

    Find the indexes of two numbers in {3, 9, 14, 5, 11} that add up to 16, in one pass.

    Show hint

    Store each value's index in an unordered_map. For each number, look up target - number.

    Show solution
    C++
    #include <iostream>
    #include <unordered_map>
    #include <vector>
    
    int main() {
        std::vector<int> nums = {3, 9, 14, 5, 11};
        int target = 16;
    
        std::unordered_map<int, int> index_of;
        for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
            if (auto it = index_of.find(target - nums[i]); it != index_of.end()) {
                std::cout << it->second << ' ' << i << '\n';
                break;
            }
            index_of[nums[i]] = i;
        }
    }
    Output
    3 4

    5 + 11 = 16: 5 is at index 3 and 11 at index 4. No earlier pair works (for example, 3 + 14 is 17).

  4. 4.Sort by score, then name

    Intermediate

    Sort the students {"Ravi", 85}, {"Asha", 92}, {"Meera", 85}, {"John", 78} by score from highest to lowest, with ties in alphabetical order, and print them.

    Show hint

    Pass a lambda comparator to std::sort that compares scores first and names second.

    Show solution
    C++
    #include <algorithm>
    #include <iostream>
    #include <string>
    #include <vector>
    
    struct Student {
        std::string name;
        int score = 0;
    };
    
    int main() {
        std::vector<Student> students = {{"Ravi", 85}, {"Asha", 92}, {"Meera", 85}, {"John", 78}};
    
        std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
            if (a.score != b.score) return a.score > b.score;
            return a.name < b.name;
        });
    
        for (const auto& s : students) std::cout << s.name << ' ' << s.score << '\n';
    }
    Output
    Asha 92
    Meera 85
    Ravi 85
    John 78
  5. 5.Balanced brackets with a stack

    Intermediate

    Check whether each of "{[()]}", "([)]" and "(()" has balanced brackets.

    Show hint

    Push opening brackets onto a std::stack<char>; each closing bracket must match the top. At the end the stack must be empty.

    Show solution
    C++
    #include <iostream>
    #include <stack>
    #include <string>
    
    bool balanced(const std::string& s) {
        std::stack<char> st;
        for (char c : s) {
            if (c == '(' || c == '[' || c == '{') {
                st.push(c);
            } else {
                char open = c == ')' ? '(' : c == ']' ? '[' : '{';
                if (st.empty() || st.top() != open) return false;
                st.pop();
            }
        }
        return st.empty();
    }
    
    int main() {
        std::cout << std::boolalpha;
        for (const char* s : {"{[()]}", "([)]", "(()"}) {
            std::cout << s << ' ' << balanced(s) << '\n';
        }
    }
    Output
    {[()]} true
    ([)] false
    (() false
  6. 6.Top three with a priority queue

    Intermediate

    Print the three largest values of {12, 45, 7, 89, 23, 56, 34} from largest to smallest, using a std::priority_queue.

    Show hint

    A std::priority_queue<int> always gives the largest element at top(). Pop three times.

    Show solution
    C++
    #include <iostream>
    #include <queue>
    #include <vector>
    
    int main() {
        std::vector<int> values = {12, 45, 7, 89, 23, 56, 34};
        std::priority_queue<int> pq(values.begin(), values.end());
    
        for (int i = 0; i < 3 && !pq.empty(); ++i) {
            std::cout << pq.top() << ' ';
            pq.pop();
        }
        std::cout << '\n';
    }
    Output
    89 56 45
  7. 7.count_if and accumulate

    Intermediate

    For {56, 91, 78, 34, 88, 91}, use algorithms (no hand-written loops) to print: the sum, how many marks are at least 75, the highest mark, and how many times it appears.

    Show hint

    Use std::accumulate (from <numeric>), std::count_if, std::max_element and std::count.

    Show solution
    C++
    #include <algorithm>
    #include <iostream>
    #include <numeric>
    #include <vector>
    
    int main() {
        std::vector<int> marks = {56, 91, 78, 34, 88, 91};
    
        int sum = std::accumulate(marks.begin(), marks.end(), 0);
        auto high = std::count_if(marks.begin(), marks.end(), [](int m) { return m >= 75; });
        int best = *std::max_element(marks.begin(), marks.end());
        auto best_count = std::count(marks.begin(), marks.end(), best);
    
        std::cout << sum << ' ' << high << ' ' << best << ' ' << best_count << '\n';
    }
    Output
    438 4 91 2