Initializing Vectors

Im trying to use a variable vector array for a variable amount of classes. I cant seem to initialize any of the vectors variables. Is there a better way to make a variable sized array? This seems like a hassle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main () {

int clsnm;
int sum=0;
cout<<"How many classes do you have?";
cin>>clsnm;
vector<int> cls[clsnm];
int loop;
loop = clsnm;
while (loop > 0) {
    loop = loop +1;
    cin>>clsnm[loop];
    sum = sum + clsnm;
}
    
}   
Last edited on
vector<int> cls[clsnm];
This appears to be an array of vectors. I think you've missed the point. Use a vector instead of an array.

Put another way, DON'T use an array. Just use a vector.

vector<int> cls(clsnm); This creates ONE vector, containing clsnm int values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
using namespace std;

int main () {

  int clsnm;
  cout<<"How many classes do you have?";
  cin>>clsnm;

  vector<int> cls(clsnm);
  
  for (int i = 0; i < cls.size(); ++i)
    {
      cout << "Enter int value " << i << ": ";
      cin >> cls[i];
    }

  for (int i = 0; i < cls.size(); ++i)
    {
      cout << "cls[" << i << "] = " <<  cls[i] << ' ';
    }
}

Last edited on
Oh. Thanks.
Last edited on
Topic archived. No new replies allowed.