2016-11-25 1 views
1

그래서이 도로 네트워크 클래스를 작성합니다.이 맵에는 연결된 꼭지점과 연결된 꼭지점 집합을 유지하는 데 사용되는지도가 포함되어 있습니다.반복자를 참조 할 수없는 목록 반복자

그것은 내가 함수 addedge를 사용하려고 할 때마다, 프로그램이 런타임 오류를 슬로우 compiled.but
struct vertex { 
     double lat; //latitude 
     double longit; //longitude 
     vertex(double lat, double longit) :lat(lat), longit(longit) {} 
}; 
struct hash_vertex { //hash function for map and set 
     unsigned operator()(const vertex& v) const { 
      string s(to_string(v.lat) + to_string(v.longit)); 
      hash<string> hash; 
      return hash(s); 
     } 
}; 
struct equal_vertex { //equal function for map and set 
     bool operator()(const vertex &v1, const vertex &v2) const { 
      return abs(v1.lat - v2.lat) + abs(v1.longit - v2.longit) < error; 
     } 
}; 
class road_network { 
    private: 
     unordered_map<vertex, unordered_set<vertex,hash_vertex,equal_vertex>, hash_vertex, equal_vertex> road; 
    public: 
     void addedge(const vertex &u, const vertex &v) { 
      auto it = *road.find(u); 
      auto it2 = *road.find(v); 
      it.second.insert(v); 
      it2.second.insert(u); 
} 
}; 

:리스트 반복자는 dereferencable하지?

누군가이 코드의 문제점을 말해 줄 수 있습니까? 미리 감사드립니다!

답변

0

올바른 결과가 있는지 테스트하지 않고 find()의 반복기 결과를 역 참조하십시오. 다음과 같이 코드를 변경하십시오.

 auto it = road.find(u); 
     auto it2 = road.find(v); 
     if(it != road.end() && it2 != road.end()) { 
      it->second.insert(v); 
      it2->second.insert(u); 
     } 
+0

ok,하지만 처음에 요소를 추가하는 방법을 알려주시겠습니까? – xpirad

+0

@xpirad 무슨 뜻인지 모르겠다. –

+0

신경 쓰지 마라, 나도 알아. – xpirad

0

당신은 그것을 역 참조하기 전에 find의 결과를 확인해야합니다 : 그것은 end 반복자를 반환하는 요소를 찾아 그 역 참조하면 정의되지 않은 동작입니다 수 없습니다

auto it = road.find(u); 
if (it != road.end()) { auto x = *it;} 

find합니다.