[英]STL map changed size automatically
I've created a map mp and inserted just one key and value to it.我创建了一个 map mp 并只插入了一个键和值。 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. 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 else if 条件,因为现在存在键 0。 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; map 的operator[]
将默认构造任何缺失的元素; see cppreference for this explicitly.明确地参见cppreference 。 To check if there is an element present in the map you have a few options:要检查 map 中是否存在元素,您有几个选项:
if (map.find(elem).= map.end())
使用if (map.find(elem).= map.end())
map.at(elem)
and catch the exception that is raised if the element does not exist使用map.at(elem)
并捕获元素不存在时引发的异常if (map.count(elem) > 0)
to check the number of occurrences of the key in the map使用if (map.count(elem) > 0)
检查 map 中键的出现次数I have listed these in (roughly) descending order of personal preference.我已经按个人喜好(大致)降序列出了这些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.