How to create a hash from two equal-length vectors (keys and values) in C++

1 Answer

0 votes
// Create a hash‑like structure from two equal‑length vectors 
// by pairing each key with the corresponding value. 

#include <iostream>
#include <unordered_map>
#include <map>
#include <vector>
#include <string>

// ------------------------------------------------------------
// Create an unordered_map (hash map)
// ------------------------------------------------------------
std::unordered_map<std::string, int> make_unordered_map(
    const std::vector<std::string>& keys,
    const std::vector<int>& values)
{
    std::unordered_map<std::string, int> result;

    for (size_t i = 0; i < keys.size(); ++i) {
        result[keys[i]] = values[i];
    }

    return result;
}

// ------------------------------------------------------------
// Create an ordered map (sorted by key)
// ------------------------------------------------------------
std::map<std::string, int> make_ordered_map(
    const std::vector<std::string>& keys,
    const std::vector<int>& values)
{
    std::map<std::string, int> result;

    for (size_t i = 0; i < keys.size(); ++i) {
        result[keys[i]] = values[i];
    }

    return result;
}

// ------------------------------------------------------------
// Create a vector of pairs (preserves order, allows duplicates)
// ------------------------------------------------------------
std::vector<std::pair<std::string, int>> make_vector_pairs(
    const std::vector<std::string>& keys,
    const std::vector<int>& values)
{
    std::vector<std::pair<std::string, int>> result;

    for (size_t i = 0; i < keys.size(); ++i) {
        result.emplace_back(keys[i], values[i]);
    }

    return result;
}

// ------------------------------------------------------------
// Main program demonstrating all three
// ------------------------------------------------------------
int main() {
    std::vector<std::string> keys   = {"a", "b", "c"};
    std::vector<int> values         = {1, 2, 3};

    // Build each structure
    auto umap  = make_unordered_map(keys, values);
    auto omap  = make_ordered_map(keys, values);
    auto vpairs = make_vector_pairs(keys, values);

    // Print unordered_map (order is not guaranteed)
    std::cout << "unordered_map:\n";
    for (const auto& kv : umap) {
        std::cout << "  " << kv.first << " => " << kv.second << "\n";
    }

    // Print ordered map
    std::cout << "\nordered map:\n";
    for (const auto& kv : omap) {
        std::cout << "  " << kv.first << " => " << kv.second << "\n";
    }

    // Print vector of pairs
    std::cout << "\nvector of pairs:\n";
    for (const auto& kv : vpairs) {
        std::cout << "  " << kv.first << " => " << kv.second << "\n";
    }
}


/*
run:

unordered_map:
  c => 3
  b => 2
  a => 1

ordered map:
  a => 1
  b => 2
  c => 3

vector of pairs:
  a => 1
  b => 2
  c => 3
  
*/

 



answered 3 hours ago by avibootz
...