繁体   English   中英

如何创建一个以数字范围为键的 unordered_map | C++

[英]How to create an unordered_map with a range of numbers as keys | C++

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

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

我想用 1 到 5 的键初始化 map

这将使键 [1, 5] map 的值为 0:

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

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

例子:

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});
}

您可以像这样使用std::generate_n

int main()
{
    std::unordered_map<int, int> um;

    std::generate_n(std::inserter(um, std::begin(um)), 5, [i = 1]()mutable{
        return std::make_pair(std::exchange(i, i + 1), 0);
    });

    for(auto& p: um)
        std::cout << p.first << ": " << p.second << '\n';
}

Output:

5: 0
4: 0
3: 0
2: 0
1: 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM