Vector

hi,
im doing some exercise to understand more about vector
but when i compile the code nothing come out and there is no error in the code.
can you guys point out what is my mistake?

p/s im totally new to this language.

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
#include <iostream>
#include<vector>
using namespace std;

class Student {
  string name;
 public:
  void setName (string name) { this->name = name; }
  string getName() const     { return name; }
};

int main() {

  vector<Student> students;
  string name;

 for (int i = 0; i < students.size(); i++) {
    cout << "Student #" << i+1<< " : Enter name = ";
    cin >> name;
    Student student;
    student.setName(name);
    students.push_back(a);
  }

  for (int i = 0; i < students.size(); i++)
    cout << "Student #" << i+1<< " : Name = "
         << students[i].getName() << endl;

  return 0;
}
Your loops won't execute because students.size() is zero.

thanks for point it out.
will to adjust the code.
I have hard time understanding what this line does:

students.push_back(a);

What exactly is a?
Shouldn't it be..
students.push_back(student); or something like that?
Last edited on
There is no declaration for "a", so the compiler should stop on error. Yes, pushing "student" sounds more proper.
If you are trying to learn vectors check out this page
http://www.cplusplus.com/reference/vector/vector/
and something to play with would be this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
vector<unsigned int> vec;
    string size, error;

    do {
        error = "false";
        cout << "How many numbers would you like to input into the vector?\nSize: " << flush;
        getline(cin,size);
        for(unsigned int i = 0; i<size.size(); i++) if(isalpha(size[i])) error = "true";
    } while(error == "true");
    string nums[atoi(size.c_str())];
    do {
        error = "false";
        for(unsigned int i = 0; i<(unsigned int)atoi(size.c_str()); i++){
            cout << "Number " << i+1 << ": " << flush;
            getline(cin,nums[i]);
        }
        for(unsigned int i = 0; i<(unsigned int)atoi(size.c_str()); i++) for(unsigned int j = 0; j<nums[i].size(); j++) if(isalpha(nums[i][j])) error = "true";
    } while(error == "true");
    for(unsigned int i = 0; i<(unsigned int)atoi(size.c_str()); i++) vec.push_back((unsigned int)atoi(nums[i].c_str()));

    for(unsigned int i = 0; i<(unsigned int)vec.size(); i++) cout << vec[i] << endl;

Last edited on
Topic archived. No new replies allowed.