My assignment was to create an empty vector of integer type. Then it would use a "for" loop to prompt the user to enter 20 integers and stores them in the vector (using the "push_back" function inside the for loop to add the new entered number to the vector). It will then print the contents of the vector to the screen using another for loop.
Then it asks the user to enter a number to delete from the vector and stores that number in a temporary variable. The program will locate the position of the entered number in the vector.
After all of that, using the pos value, delete that value from the vector (only the first occurence). Use an if statement to first determine if the value was found based on the value of pos (which will be negative if the number was not found).
Finally, you must print thenew contents of the vector!
If someone could show me the code they use for this, it would be greatly appreciated. I have a code and it runs fine but I know there has to be an easier way to do it. My code is very very long :(
Thanks!!
#include <iostream>
usingnamespace std;
int main()
{
my_vec[];
int input;
for (int j=0; j<20; j++)
{
cout << "Enter a number: ";
cin >> input;
my_vec.push_back(input);
}
//prints to scree with for loop
int num;
cout << "Please enter a number to be deleted from vector: ";
cin >> num;
int pos = -1;
for (int m=0; m < my_vec.size(); m++)
{
if (my_vec[m] == num)
{
pos = m;
break;
}
}
if (pos >= 0)
{
for (int x = pos; x < my_vec.size() - 1; x++)
{
my_vec[x] = my_vec[x + 1];
}
my_vec.pop_back();
}
else
{
cout << "\n\nThe number was not found.\n\n";
}
//print new contents to screen
}
I cannot get it to run anymore because I had to redo it. Where the comments are I need to print the vector contents to the screen and I'm not sure how I got that to work last time.