简体   繁体   中英

STL map changed size automatically

I've created a map mp and inserted just one key and value to it. When I call the DFS function and get into it, initially the map size is shown as 1. However after the first if condition in DFS, the map adds a new key-value pair {0,0} to the existing map and goes into the else if condition because now a key 0 exists. Here's the code I've written

#include<vector>
#include<map>
#include<iostream>

using namespace std;

vector<bool> visited;
map<int, int> mp;

bool flag = true;

void DFS(int key)
{
    if (visited[key])
    {
        flag = false;
        return;
    }

    else if (mp.count(mp[mp[key]]) > 0)
    {
       
        visited[key] = true;
        DFS(mp[key]);
    }
}

bool canFinish(int numCourses, vector<vector<int>>& prerequisites)
{

    for (int i = 0; i < numCourses; i++)
    {
        visited.push_back(false);
    }

    for (auto prereq : prerequisites)
    {
        std::cout << prereq[0] << " "<<prereq[1] << "\n";
        mp.insert({ prereq[0],prereq[1] });
    }


    for (int i = 0; i < prerequisites.size(); i++)
    {
        DFS(prerequisites[i][0]);
        if (!flag) return false;
    }

    return true; 
}

int main()
{
    vector<vector<int>> prerequisites{ {1,0} };
    std::cout << canFinish(2, prerequisites);

}

operator[] for map will default construct any missing elements; see cppreference for this explicitly. To check if there is an element present in the map you have a few options:

  • Use if (map.find(elem).= map.end())
  • Use map.at(elem) and catch the exception that is raised if the element does not exist
  • Use if (map.count(elem) > 0) to check the number of occurrences of the key in the map

I have listed these in (roughly) descending order of personal preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM