我收到运行时错误,说矢量迭代器不兼容。
#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;
}
答案 0 :(得分:4)
it2 !=Interval1.end()
将Interval2
的迭代器与Interval1
的迭代器进行比较 - 这是非法的。
假设这只是一个拼写错误,只需将其更正为it2 != Interval2.end()
。
答案 1 :(得分:1)
您将it2
与Interval1.end()
进行比较:
while(it1 != Interval1.end() && it2 !=Interval1.end())
应该有:
while(it1 != Interval1.end() && it2 !=Interval2.end())