为什么此代码会导致分段错误?

 #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <string>

using namespace std;

int n = 17;
vector < string > ports (n, "");
vector < string > checked (ports);
multimap < string, string > routes;

void check_routes (string x)
{
  for (vector < string >::iterator it1 = checked.begin ();it1 != checked.end (); it1++)
    {
      if (*it1 == x)
    {
      checked.erase (it1);
    }
    }
  for (multimap < string, string >::iterator it = routes.begin ();
       it != routes.end (); it++)
    {
      if (it->first == x)
    {
      check_routes (it->second);
    }
    }
}


int
main ()
{
  int ans = 0;
  ports.push_back ("BUD");
  ports.push_back ("BGI");
  ports.push_back ("DEL");
  ports.push_back ("DOH");
  ports.push_back ("DSM");
  ports.push_back ("EWR");
  ports.push_back ("EYW");
  ports.push_back ("HND");
  ports.push_back ("ICN");
  ports.push_back ("JFK");
  ports.push_back ("LGA");
  ports.push_back ("LHR");
  ports.push_back ("ORD");
  ports.push_back ("BSAN");
  ports.push_back ("SFO");
  ports.push_back ("SIN");
  ports.push_back ("TLV");
  routes.insert (make_pair ("DMS", "ORD"));
  routes.insert (make_pair ("ORD", "BGI"));
  routes.insert (make_pair ("BGI", "LGA"));
  routes.insert (make_pair ("SIN", "CDG"));
  routes.insert (make_pair ("CDG", "SIN"));
  routes.insert (make_pair ("CDG", "BUD"));
  routes.insert (make_pair ("DEL", "DOH"));
  routes.insert (make_pair ("DEL", "CDG"));
  routes.insert (make_pair ("TLV", "DEL"));
  routes.insert (make_pair ("EWR", "HND"));
  routes.insert (make_pair ("HND", "ICN"));
  routes.insert (make_pair ("HND", "JFK"));
  routes.insert (make_pair ("ICN", "JFK"));
  routes.insert (make_pair ("JFK", "LGA"));
  routes.insert (make_pair ("EYW", "LHR"));
  routes.insert (make_pair ("LHR", "SFO"));
  routes.insert (make_pair ("SFO", "SAN"));
  routes.insert (make_pair ("SFO", "DSM"));
  routes.insert (make_pair ("SAN", "EYW"));
  for (int i = 0; !(checked.empty ()); i++)
    {
      check_routes (checked[i]);
      ans++;
    }
  cout << ans;
  cout << "Hello world!" << endl;
  return 0;
}

因此,我试图解决在网上发现的机场接驳问题,这就是我的看法。但是我无法弄清楚代码中的错误所在。如果有人可以帮助我,我将不胜感激。 (PS问题是这样的-我有机场(矢量端口)列表以及这些端口(多地图路线)之间的一种单向连接,并且我需要找出我需要进行连接的最少数量所有端口(连接的长度无关紧要).............该代码应该做的是找到单个端口/网络的数量。互连端口,我相信这会给我所需的答案,因为我要做的就是从每个链中连接一个节点)

评论
JJ初始化
JJ初始化

这是遍历列表时修改列表的常见问题。您从列表中删除或移动元素,这意味着该列表成为另一个列表,需要您进行其他操作。最后,您会发现您访问的元素或位置超出范围。我认为,您需要改变对这个问题的看法。

点赞
评论