【问题标题】:unordered_map not iterating all keysunordered_map 没有迭代所有键
【发布时间】: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


【解决方案1】:

这是因为您正在更改您正在迭代的地图。这样做时必须小心,因为如果在 emplace 期间发生重新散列,所有迭代器都会失效。

【讨论】:

  • 我无法理解我在哪里更改地图。你能告诉我线路吗?
  • @saha G[curr] 将插入一个条目,如果 curr 的值还不是映射中的键。这样你就可以拥有G['c'].emplace('b');
【解决方案2】:

您最初的尝试是修改地图,为a 添加一个条目。第二次尝试抛出异常,未能找到a 的条目。

当值不在地图中时,听起来您想结束搜索。

void DFS(const char curr, const unordered_map<char, unordered_set<char>>& G) {
    cout << "Traversing: " << curr << endl;
    auto it = G.find(curr);
    if (it != G.end()) {
        for(auto ch: it->second) {
            DFS(ch, G);
        }
    }
}

或者,您可以初始化映射中的a 条目,这三个选项中的任何一个都可以使用(尽管非const 版本是最不安全的,因为当您找不到时会出现未定义的行为)

int main() {
    std::unordered_map<char, std::unordered_set<char>> G;

    G['c'].emplace('b');
    G['b'].emplace('a');
    G['a'];

    for(auto it : G) {
        cout << "Starting with: " << it.first << endl;
        DFS(it.first, G);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多