首页 > 解决方案 > 如何创建一个以数字范围为键的 unordered_map | C++

问题描述

int n;
unordered_map<int,int> map(1,n); 

这给了我错误。我想用从 1 到 n 的键来初始化地图。我怎样才能做到这一点?

标签: c++stlunordered-mapc++-standard-library

解决方案


我想用从 1 到 5 的键来初始化地图

这将使键 [1, 5] 映射到值 0:

std::unordered_map<int,int> map{
    {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}
};

如果您需要许多键,使用所有键初始化映射可能太麻烦了,在这种情况下,您将不得不使用某种循环。

例子:

for(int i = 1; i < 1000; ++i) map[i] = 0;

如果您想隐藏将使用某种循环的事实,您可以使用unordered_map接受迭代器并提供一对计数迭代器的构造函数。我想你会找到你需要的,boost或者你可以自己为此目的编写一个特殊的迭代器:

#include <cstdint>
#include <iterator>
#include <utility>

template<class T, class U>
struct keygen {
    using iterator_category = std::forward_iterator_tag;
    using value_type = std::pair<T,U>;
    using pointer = value_type*;
    using referece = value_type&;
    using difference_type = std::intmax_t;

    keygen& operator++() { ++key; return *this; }
    keygen operator++(int) { auto copy=*this; ++key; return copy; }
    bool operator==(const keygen& rhs) const { return key == rhs.key; }
    bool operator!=(const keygen& rhs) const { return key != rhs.key; }

    std::pair<T,U> operator*() const { return {key, value}; }

    T key;
    U value;
};

int main() {
    // map initialized with keys 1-1000 that maps to 0:
    std::unordered_map<int,int> map(keygen<int,int>{1,0}, keygen<int,int>{1001,0});
}

推荐阅读