在地图内设置for循环迭代

时间:2019-07-03 14:30:59

标签: c++

我是cpp的新手,请帮忙,在cpp中出现循环错误,我想遍历set 如下所示。

vector<vector<int>> verticalTraversal(TreeNode* root) {

    map<int, map<int, set<int>>> mep;

    solve(root, 0, 0, mep);
    vector<vector<int>> result;
    for (auto p : mep) {
        vector<int> temp;
        auto s = p.second;
        for (auto ity = s->second.begin(); ity != s->second.end(); it++) {
            //getting here error in second above
        }

        //reverse(temp.begin(), temp.end());
        result.push_back(temp);
    }
    return result;
}

2 个答案:

答案 0 :(得分:2)

在您的代码中:

for (auto ity = s->second.begin(); ity != s->second.end(); it++) {
          ^^^                      ^^^                     ^^

您声明ity,但使用ityit

答案 1 :(得分:0)

在这里您声明ity但使用it

for (auto ity = s->second.begin(); ity != s->second.end(); it++)

让生活更轻松的一种方法是使用range-based for loopsstructured binding

vector<vector<int>> verticalTraversal(TreeNode* root) {
    map<int, map<int, set<int>>> mep;

    solve(root, 0, 0, mep);
    vector<vector<int>> result;

    // structured binding in a range-based for loop below
    for (const auto& [an_int, inner_map] : mep) {
        vector<int> temp;

        // structured binding in a range-based for loop below
        for(const auto& [another_int, a_set] : inner_map) {
            for(int inner_int : a_set) {
                // ...
            }
        }

        //reverse(temp.begin(), temp.end());
        result.push_back(temp);
    }
    return result;
}