my code gives me a runtime error "vector iterator not incrementable"
here is my code and I'm pretty sure the problem is in the first function but I can't put my hands on what's wrong.
by the way I'm still learning ,I know there
might be better ways to achieve the result I want but that's what I've learned so far
#include <D:\\std_lib_facilities.h>
#include <vector>
vector<int> filter (int num,char sign,vector<int> nums)
{
if (sign == '>')
{
int counter = 0;
for (int x : nums)
{
if (x < num)
{
nums.erase(nums.begin() +counter);
}
++counter;
}
}
elseif (sign == '<')
{
int counter = 0;
for (int x : nums)
{
if (x > num)
{
nums.erase(nums.begin() + counter);
}
++counter;
}
}
return nums;
}
int main()
{
vector <int> numbers;
int i = 0;
//fill the vector with ints from 1-100
while (i < 100)
{
numbers.push_back (i+1);
++i;
}
char choice ;
cout << "is the number smaller than 50 (y/n)\n";
cin >> choice;
if (choice == 'y')
{
//this is suposed to filter ints in verctor numbers and remove all numbers above 50
for (int k : filter(50, '<', numbers))
cout << k << " ";
}
}
To reinforce what @keskiverto said, it is in fact illegal ("results in undefined behavior" is the idiom we tend to use) to perform any operation which can invalidate an iterator while in a range-based for loop.
Thanks for the reply
now I refined the function but I have a small problem with the else if (sign == '<') when the vector contains these values (32,34,36) it gives a range error I am a beginner don't know what does that even mean
this happens when the function arguments are
filter(34,'>',(and the vector that contains the elements above))