(Public / Wikimedia Commons)

Education

Column: std::map vs. std::set

The difference between two C++ Standard containers
<a href="https://highschool.latimes.com/author/johnsong415/" target="_self">John Song</a>

John Song

December 31, 2021
C++ Standard has various containers, two of which are std::map and std::set. What’s the difference between them and when do we use which?

Imagine a club in your school, where there are 30 members and 5 of them are officers. You want a data structure of members, keyed (indexed) by student ID, meaning you can quickly find students using their ID. You probably want to use std::map for this type of use case — std::unordered_map may be better if you don’t care about the order, which means you want to find a student quickly by ID, but don’t really need to list them up sorted by ID.

(John Song)

In the club, let’s say you want to keep a separate “set” of students that are officers. You already have a data structure (std::map or std::unordered_map) that has the information of all students, so you only want to keep separate data of “who are officers.” In this case, you probably want to consider a std::set of student IDs. This is basically like a set in Math.

(John Song)

(John Song)

If you want a data structure that supports key/value pairs, std::map (or std::unordered_map) is probably what you’re looking for. If you only care about keys without values (you want to find an element quickly, but you don’t need any data associated with it), then std::set (or std::unordered_set) will be the one you’d want to use.

Here’s a quick bit of sample code using the above example:

(John Song)

(John Song)

Output:

(John Song)

(John Song)

A full and detailed reference for both containers can be found here: http://en.cppreference.com/w/cpp/container

Opinion: An Assault on Education

Opinion: An Assault on Education

Earlier last month, the Supreme Court struck down race-conscious admissions in cases against Harvard and the University of North California. Just one day later, they ruled that the Biden Administration overstepped with their plan to wipe out $400 billion in student...