2012-03-16 79 views
0

我得到一個運行時錯誤,說明向量迭代器不兼容。向量迭代器不兼容(運行時錯誤)

#include <iostream> 
#include <vector> 

using namespace std; 


struct Interval 
{ 
public: 
    Interval(int s,int e):start(s),end(e) {} 
    int start; 
    int end; 

}; 


void merge_intervals(vector<Interval>& Interval1, vector<Interval>& Interval2, vector<Interval>& merged) 
{ 
    int i = 0 ; 
    cout<<"i"<<i<<endl; 
    vector<Interval>::iterator it1 = Interval1.begin(); 

    vector<Interval>::iterator it2 = Interval2.begin() ; 

    while(it1 != Interval1.end() && it2 !=Interval1.end()) 
    { 
     cout<<"i"<<i<<endl; 
     i++; 
     if(it1->start <= it2->start) 
     { 

      if(it1->end <= it2->end) 
      { 
       it1++; 
       merged.push_back(*it1); 
      } 
      else 
      { 
       it1++; 
       it2++; 
       merged.push_back(Interval(it1->start,it2->end)); 
      } 
     } 
     else 
     { 
      if(it1->end >= it2->end) 
      { 
       it2++; 
       merged.push_back(*it2); 
      } 
      else 
      { 
       it1++; 
       it2++; 
       merged.push_back(Interval(it2->start,it1->end)); 
      } 
     } 

     while(it1 != Interval1.end()) 
     { 
      merged.push_back(*it1); 
      *it1++; 
     } 

     while(it2 != Interval2.end()) 
     { 
      merged.push_back(*it2); 
      *it2++; 
     } 
    } 
} 

void print_intervals(vector<Interval>& merged) 
{ 
    vector<Interval>::iterator it = merged.begin(); 

    for(it = merged.begin();it != merged.end(); ++it) 
    { 
     cout<<"("<<it->start<<","<<it->end<<")"<<endl; 
    } 
} 

void test1() 
{ 
    vector<Interval> Interval1, Interval2, merged ; 

    Interval1.push_back(Interval(1,4)); 
    Interval1.push_back(Interval(6,10)); 
    Interval1.push_back(Interval(14,19)); 

    Interval2.push_back(Interval(13,17)); 

    merge_intervals(Interval1, Interval2, merged); 
    print_intervals(merged); 

} 

int main() 
{ 
    test1(); 
    return 0; 
} 
+6

這是什麼都與'採訪-questions'辦? – 2012-03-16 22:48:28

回答

4

it2 !=Interval1.end()Interval2迭代器從Interval1 –比較進行迭代的迭代,這是非法的。

假設這只是一個錯字,只需將其更正爲it2 != Interval2.end()即可。

+0

感謝您的幫助。它是我的壞我無法找到一個簡單的錯誤。 – mousey 2012-03-16 23:05:07

1

你比較it2Interval1.end()

while(it1 != Interval1.end() && it2 !=Interval1.end()) 

應該有:

while(it1 != Interval1.end() && it2 !=Interval2.end())