Search code examples
c++classoop

can anyone tell me how can I create multiple objects using vector without specifying the length of vector


I tried to do it using the vector<string> and iterating through it to create the object but while assigning them value i am getting error



#include <iostream> 
#include <string>   
#include <vector>   

class Student {
public:
    std::string name;
    int rollno;
    void display(){
        std::cout << "Name of student is "<<name<< "\nHis Roll Number is " << rollno << "\n";
    }
};

int main() {
    std::vector<Student> students(10); 
    for (int i = 0;i <10;i++){
        std::string temp;
        std::cout << "Enter name for student " << (i + 1) << ": ";
        std::cin >> temp;
        students[i].name = temp;
    }

    for (int i = 0; i < 10; i++) {
        int x;
        std::cout <<"Enter roll number for student "<<(i + 1)<<": ";
        std::cin>>x;
        students[i].rollno=x;
    }

    
    for(int i = 0; i < 10; i++) {
        students[i].display();
    }

    return 0;
}

Edit : All that I want ask is if there is any way to take input from user then make an object with same input as name and store that name in vector<Student> and use this vector to iterate through the list of objects


Solution

  • It sounds like your input is a list of names followed by a list of id numbers. If that's the case, wouldn't you really just want this:

    int main() {
        std::vector<Student> students;
    
        for (int i = 0; i < 10; i++) {
            string name;
            cin >> name;
            Student s;
            s.name = name;
            students.push_back(s);
        }
        for (int i = 0; i < 10; i++) {
            int x;
            cin >> x;
            students[i].rollno = x;
        }
        return 0;
    }
    

    And if you want to optimize further, add a constructor to Student as follows:

    class Student {
    public:
    
        ...
    
        Student(const std::string& n) : name(name), rollno(-1) {
        }
    
        ...
    
    
    

    Such that your first for-loop can be optimized as follows:

    for (int i = 0; i < 10; i++) {
        string name;
        cin >> name;
        students.emplace_back(Student(name));
    }
    

    Then your second loop that adds the roll id number stays the same.