C++ Code problem using vectors

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!!
Post your code, then, and we can help you figure out how to make it better.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
using namespace 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.
That's an array not a vector. You need to add #include<vector> into your header to use a vector.

Vectors are initialized like this:

vector<type>name;

Because it's an array, push_back doesn't work.

On the note of arrays, you have to specify the array length upon initialization. Your [] is empty. Also you need to declare the type of the array.
Topic archived. No new replies allowed.