I have written a short code that uses a while loop to go through a (sorted!) vector of structures and inserts a new element based on its price (if there is already an entry for a specific price, the new entry should be inserted behind the existing entry.
Using g++
and Sublime Text 3 everything works (output at the end of this question), but using Visual Studio 2015 I get the error: Debug Assertion Failed! ... Expression: vector iterator not dereferencable
. (note that this error only surfaces if the new element should be attached at the end of the existing vector, if we change the new element to struc newEl = {5, 2.0}
everything works fine with both VS and g++
).
The code looks like this:
#include <iostream>
#include <vector>
struct struc {
int num;
double price;
};
int main() {
std::vector<struc> v = { { 1, 1.5 },{ 2, 1.6 },{ 3, 2 },{ 4, 2.6 } };
struc newEl = { 5, 2.7 };
std::vector<struc>::iterator it = v.begin();
while (((*it).price <= newEl.price) && (it < v.end())) {
it++;
}
v.insert(it, newEl);
for (struc vec : v) {
std::cout << vec.num << ", " << vec.price << std::endl;
}
std::cout << "Finished";
return 0;
}
The output should be (and is in the case of g++
and ST):
1, 1.5
2, 1.6
3, 2
4, 2.6
5, 2.7
Finished
Now my question is, what causes the error in VS and what do I need to change to make it work in VS?
Thank you very much!