(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

Column: This winter, encourage eating

Column: This winter, encourage eating

Every December, malls wrap their fake indoor plants in silver tinsel, radio stations blast Christmas carols with different beats but the same lyrics, and people from Southern California convince themselves that 65 degrees is below freezing and worthy of a scarf, mug...

B4L changes its look

B4L changes its look

The slogan “Baron For Life” is intertwined throughout the Fountain Valley High School campus and culture. It finds itself embedded in speeches, posters and most prominently in the B4L raffle here at FVHS. The four B4L values of being considerate, analytical, curious...