I have the following code
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval)
{
vector<Interval> res;
vector<Interval>::iterator it;
for (it = intervals.begin(); it != intervals.end(); it++)
{
if (newInterval.start < (*it).start)
{
intervals.insert(it, newInterval);
break;
}
}
if (it == intervals.end()) //---->vector iterator incompatible
{
intervals.insert(it, newInterval);
}
}
I am getting an error of vector iterator incompatible at the statement
if (it == intervals.end()) //---->vector iterator incompatible
{
intervals.insert(it, newInterval);
}
Can anyone please clarify why this is happening and how I can fix this? Also this happens even when insert is not called. This is the error that i get
The iterator is invalidated with insert
(For vector, an insertion may cause the memory reallocation, all elements are moved to a new address. The iterator is just a pointer, so it can't be used to compare with the new end of a vector, it's meaningless), as the comment mentioned, you need to reassign the return value to the it
value. Or just simplified the code with std::find_if
, it's preferred to use STL algorithms over hand write loop. To make code clear and more maintainable.
#include <algorithm>
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res;
if (auto itr = std::find_if(intervals.begin(), intervals.end(),
[&newInterval](const Interval& val) {
return newInterval.start < val.start;
});
itr != intervals.end()) {
intervals.insert(itr, std::move(newInterval));
} else {
intervals.push_back(std::move(newInterval));
}
// omitted
return res;
}
Or just simplify as:
#include <algorithm>
vector<Interval> insert2(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res;
auto itr = std::find_if(intervals.begin(), intervals.end(),
[&newInterval](const Interval& val) {
return newInterval.start < val.start;
});
intervals.insert(itr, std::move(newInterval));
// omitted
return res;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.