【发布时间】:2019-02-11 05:07:35
【问题描述】:
我有以下代码来迭代 unordered_map 中的所有键,同时我将映射传递给其他函数。由于某种原因,迭代器无法遍历所有键。我无法弄清楚为什么以及如何解决这个问题。如果我将地图作为值而不是引用传递,那么它会按预期工作,但我想通过引用传递以保存副本。
代码:
void DFS(char curr, unordered_map<char, unordered_set<char>>& G) {
cout << "Traversing: " << curr << endl;
for(const char& ch: G[curr]) {
DFS(ch, G);
}
}
int main() {
unordered_map<char, unordered_set<char>> G;
G['c'].emplace('b');
G['b'].emplace('a');
for(auto it : G) {
cout << "Starting with: " << it.first << endl;
DFS(it.first, G);
}
}
我得到的输出是:
Starting with: b
Traversing: b
Traversing: a
注意不是遍历keyc。
更新: 更改 DFS 函数以使地图 const 如下所示也无济于事:
void DFS(const char curr, const unordered_map<char, unordered_set<char>>& G) {
cout << "Traversing: " << curr << endl;
for(auto ch: G.at(curr)) {
DFS(ch, G);
}
}
它也抛出异常:
terminate called after throwing an instance of 'std::out_of_range'
what(): _Map_base::at
【问题讨论】:
-
DFS是否应该修改G?如果没有,请将其设为const并修复出现的错误。如果是这样,你能解释一下为什么你期望它遍历c? -
更改为常量也无济于事,而是导致异常。请参阅更新部分。我希望
c可以从main函数中遍历,因为它也是一个键。 -
好的,所以你不要指望
DFS修改G。然而它是,导致异常。你知道如何在你的平台上调试异常吗?
标签: c++ unordered-map