c++ - 如何创建一个以数字范围为键的 unordered_map | C++
问题描述
int n;
unordered_map<int,int> map(1,n);
这给了我错误。我想用从 1 到 n 的键来初始化地图。我怎样才能做到这一点?
解决方案
我想用从 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});
}
推荐阅读
- python-3.x - 逻辑回归 SKLEARN 无法将字符串转换为浮点数:“DailyReturns”
- dialogflow-es - Actions on Google,如何在 Action 流式传输 MP3 时更改音量?
- matlab - 如何在 Matlab(或任何其他语言)中对稀疏矩阵进行二进制线性代数?
- javascript - 如何解压缩 Gunzip 以及如何将对象解析为 Json?
- django - 使用 Prefetch 提高具有数百万行的子查询中的计数性能
- c# - 从下拉列表中选择值后出现空异常,值不能为空
- c++ - 构造接受任何可迭代类型的 std::hash 函数
- javascript - 将嵌套数组添加到 Sequelize/PostgreSQL 数据库
- r - 在 R 中分组、变异和显示期望值的问题
- c# - 当我从拖动中释放位图时,如何防止位图闪烁?