CodeBlanks Logo Icon CodeBlanks

Summary - STL containers

Combine vector, map and set to write a phone book.

Summary - STL containers

In this group you learned five core STL containers. std::vector is a dynamic array, std::list a doubly linked list, std::map an ordered key-value store, std::unordered_map a hash table, std::set a unique sorted set.

In the final task you'll combine vector and set: create a vector with duplicate elements, then build a set from it. The set ignores duplicates, so its size gives the unique count. This is a common container-composition pattern.

Practice Mini task: combine vector and set

Create std::vector<int> v;; add 1, 2, 2, 3 with push_back. Build std::set<int> s(v.begin(), v.end());. Print s.size().

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <set>

// add 1, 2, 2, 3 to a vector
// create a set from the vector

int main() {
    // print the set size
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <set>

int main() {
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(2);
    v.push_back(3);
    std::set<int> s(v.begin(), v.end());
    std::cout << s.size() << std::endl;
    return 0;
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which container for fast O(1) access when order doesn't matter?

main.cpp
// anahtar-değer, sıralama önemli değil
  • std::map
  • std::set
  • std::list
  • std::unordered_map Correct answer

Explanation: unordered_map offers average O(1) access; no ordering.

2 Match container to property

Term Meaning
std::vector Dynamic array
std::list Doubly linked list
std::map Ordered key-value
std::set Unique sorted

3 Key-value container

Question
std::____<std::string, int> m;
Answer
std::map<std::string, int> m;

Explanation: std::map<std::string, int> m; is an ordered key-value container.

All lessons in Intermediate