Beginner vector question

So I was under the impression that using vectors would allow the user to specify the size of the vector during program execution and it does....but only if I make the vector size bigger than what the user enters. Is there a way for the user to specify the size of the vector without having me making the vector ridiculously huge to accommodate the user. I know arrays can't do it which is why I am trying to learn vectors. Thanks for any feedback!


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
//VECTOR program...messing around
//book says user can specify vector size...unlike arrays where they are static
#include "iostream"
#include "string"
#include <vector>
using namespace std;

int main()
{
    int j,vectorSize=500;

    cout<<"-- Outputting a vector --"<<endl;

    vector<int> intList(vectorSize);

    //user gets to specify however many numbers he/she wants
    cout <<"How mnay numbers will you be using: ";
    cin >>vectorSize;
    cout<<endl;

    //user inputs numbers
    for(j=0;j<vectorSize;j++)
    {
    cout<<"Enter a number: ";
    cin>>intList[j];

    }

    //output numbers
    cout<<endl<<endl<<"-- Vector List --"<<endl<<endl;
    for(int j = 0; j < vectorSize; j++)
        cout << intList[j]<<" ";
        cout<<endl<<endl;
    return 0;
}
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
#include "iostream"
#include "string"
#include <vector>
using namespace std;

int main()
{

    cout<<"-- Outputting a vector --"<<endl;


    //user gets to specify however many numbers he/she wants
    cout <<"How mnay numbers will you be using: ";
    int vectorSize(0);
    cin >>vectorSize;
    cout<<endl;

    vector<int> intList(vectorSize);
    // STATIC ARRAY
    int aList[vectorSize];
    //user inputs numbers
    for(int j=0;j<vectorSize;j++)
    {
        cout<<"Enter a number: ";
        cin>>intList[j];
        // or: cin>>aList[j];
        aList[j] = intList[j];
    }

    //output numbers
    cout<<endl<<endl<<"-- Vector List --"<<endl<<endl;
    for(int j = 0; j < vectorSize; j++)
        cout << intList[j]<<" ";
    cout<<endl<<endl;
    //output numbers STATIC ARRAY
    cout<<endl<<endl<<"-- STATIC ARRAY LIST --"<<endl<<endl;
    for(int j = 0; j < vectorSize; j++)
        cout << aList[j]<<" ";
    cout<<endl<<endl;
    return 0;
}
Don't know much about vectors, but you posted in the wrong thread. This should have been in Beginner C++ or General C++ but not Jobs.
Silly me. Thanks. Was wondering why I couldn't find my code in the beginners section. Thanks zegarek84
Topic archived. No new replies allowed.