[英]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.