Start learning free

LESSON 225 OF 281 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Lists to a Dictionary in C++: Building an unordered_map

Practice Read the full explanation

Given a vector of strings names and a vector of integers scores of the same length, pair each name with the score at the same index. Return an unordered_map where names[i] is a key and scores[i] is its value.

The names are all different, while two names can have the same score. If names and scores are empty, return an empty unordered_map. The order of the entries doesn't matter.

Example 1:

Input: names = ["Ana", "Ben", "Cara"], scores = [90, 75, 88]
Output: {"Ana": 90, "Ben": 75, "Cara": 88}
Explanation: "Ana" is at index 0 in names, and the score at index 0 is 90. The same goes for "Ben" with 75 and "Cara" with 88.

Example 2:

Input: names = ["Zoe", "Adam"], scores = [60, 60]
Output: {"Zoe": 60, "Adam": 60}
Explanation: Two names with the same score are two different entries.

Example 3:

Input: names = ["Max"], scores = [100]
Output: {"Max": 100}
Explanation: One name gives a single entry.
STEP 1 OF 4
    Ctrl + Enter to check

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in C++, explained

    Problem overview

    The function toDictionary takes a vector<string> named names and a vector<int> named scores of the same length. It returns an unordered_map<string, int> in which each names[i] is a key and scores[i] is its value. The names are all different, two names may share a score, and two empty vectors give an empty map. The order of the entries doesn't matter.

    With names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the map holds Ana: 90, Ben: 75 and Cara: 88. With ["Zoe", "Adam"] and [60, 60], it holds Zoe: 60 and Adam: 60: equal scores are fine, because only the keys must be different.

    Approach: walk both vectors with one index

    The two vectors are parallel: the name at index i belongs to the score at index i. A range-based loop would give you only one of them, so use a classic indexed loop. One index i reaches the name and its score, and the loop body stores the pair in the map. Assigning to a key that isn't in the map adds it, so each name creates its own entry.

    Step by step

    1. Create result. An empty unordered_map<string, int>, which will get one entry per name.
    2. Loop over the indexes. for (int i = 0; i < names.size(); i++) visits every position of names.
    3. Store the pair. result[names[i]] = scores[i]; uses the name as the key and the score at the same index as the value.
    4. Return result. After the loop every name has its score.

    The solution in C++

    class Solution {
    public:
        unordered_map<string, int> toDictionary(vector<string>& names, vector<int>& scores) {
            unordered_map<string, int> result;
            for (int i = 0; i < names.size(); i++) {
                result[names[i]] = scores[i];
            }
            return result;
        }
    };
    

    The C++ details worth knowing:

    • Assignment through [] inserts or overwrites. If the key is missing, result[key] creates it with a default value and the assignment then sets it. If the key already exists, the assignment replaces the old value. This lesson never repeats a name, so nothing is overwritten. With a repeated name, the later score would win.
    • The loop condition mixes types. i is a signed int and names.size() is unsigned. The comparison works for normal sizes, and a compiler may warn about it. Using size_t i avoids the mix.
    • Nothing checks the lengths. The code reads scores[i] for every index of names. If scores were shorter, that would read outside the vector, which is undefined behaviour. The task promises equal lengths.
    • Empty input is handled naturally. With empty vectors the loop never runs, and the empty map is returned.
    • Reference parameters. The & on both vectors avoids copying them.

    Complexity

    Time: O(n) on average for n names, since each insertion into an unordered_map takes constant time on average. Space: O(n), for the map with one entry per name.

    Edge cases and common mistakes

    • Empty vectors. The result has size 0.
    • Equal scores. They don't collide: ["Zoe", "Adam"] with [60, 60] gives two entries.
    • Repeated names. They would collapse into one entry holding the last score, which is why the task says the names are all different.
    • Swapping key and value. result[scores[i]] = names[i] doesn't compile for this map type, and with a different type it would lose entries whenever two scores match.
    • Expecting insertion order. The map doesn't keep the order of names.

    Testing

    Printed with the entries sorted by key:

    • ["Ana", "Ben", "Cara"] with [90, 75, 88] gives Ana: 90, Ben: 75, Cara: 88.
    • ["Zoe", "Adam"] with [60, 60] gives Adam: 60, Zoe: 60.
    • Two empty vectors give a map of size 0.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free