在vc++6.0中使用不了嵌套的map,也使用不了unordered_map,
如下
unordered_map<string, unordered_map<string, string>> oldIniMap
map<string, map<string, string>> oldIniMap
请问有什么方法能够代替嵌套map的作用,或者说vc++6.0怎样才能使用嵌套的map
在vc++6.0中使用不了嵌套的map,也使用不了unordered_map,
如下
unordered_map<string, unordered_map<string, string>> oldIniMap
map<string, map<string, string>> oldIniMap
请问有什么方法能够代替嵌套map的作用,或者说vc++6.0怎样才能使用嵌套的map
未完待续…
答案:
在vc++6.0中,由于其不支持C++11标准,不支持嵌套unordered_map,因此可以考虑使用嵌套map或其他数据结构进行替代。
例如,可以使用数组来存储嵌套map的内容,或者使用其他的数据结构如vector等。具体使用哪种数据结构,需要根据具体的应用场景来进行选择。
下面介绍一种使用嵌套map来实现树的最大宽度的方法:
假设有一个二叉树,现在需要求出其最大宽度。可以使用宽度优先遍历的方法,将每层的节点用map存储,map的key表示节点在该层的位置,value表示该节点本身。
具体步骤如下:
1.定义一个队列q,将根节点压入队列中。
2.定义一个map cur_level,在第一步时,将map的key值设为1,表示该节点在第一层,value值设为根节点。
3.定义一个变量cur_width,表示当前层的宽度,初始化为1。
4.从队列头部开始循环,每次取出一个节点,并将其左右子节点压入队列中。
5.对于每个节点,将其从map中取出,并计算其位置(可在节点结构体中加入一个成员变量来表示该节点在该层的位置),将其插入到新的map next_level中。
6.当当前节点为该层的最后一个节点时,将当前层的宽度与全局最大宽度cur_max_width比较,更新cur_max_width。
7.将next_level作为cur_level,重复步骤4-6,直到队列为空。
8.返回最大宽度cur_max_width。
代码如下:
struct Node {
int val;
Node* left;
Node* right;
int pos; // 节点在该层的位置
Node(int v) : val(v), left(NULL), right(NULL), pos(0) {}
};
int max_width(Node* root) {
if (root == NULL)
return 0;
queue<Node*> q;
q.push(root);
map<int,Node*> cur_level;
cur_level[1] = root;
int cur_width = 1, cur_max_width = 1;
while (!q.empty()) {
Node* cur = q.front();
q.pop();
if (cur->left != NULL) {
cur->left->pos = cur->pos * 2 - 1;
q.push(cur->left);
cur_level[cur->left->pos] = cur->left;
}
if (cur->right != NULL) {
cur->right->pos = cur->pos * 2;
q.push(cur->right);
cur_level[cur->right->pos] = cur->right;
}
if (cur->pos == cur_width) {
cur_width = (cur_level.rbegin()->first - cur_level.begin()->first) / 2 + 1;
cur_max_width = max(cur_max_width, cur_width);
map<int,Node*> next_level;
cur_level.swap(next_level);
}
}
return cur_max_width;
}
参考资料:
杨洋.《算法面试通关40讲》.人民邮电出版社.
http://www.cplusplus.com/reference/unordered_map/unordered_map/
https://hongjingyuan.com/vc++6.0/572118.shtml