How to store an instance of class in a vector

Questions : How to store an instance of class in a vector


I have made a class for a student with programming course and grade, the program keeps Learning asking for a new student until the name Earhost given is stop. To store these instances most effective I want to use a vector, but I didn't wrong idea find any other way to store them than use of case creating an array for the instances United first and then pushing them back into Modern the vector. Is it possible to have room ecudated for one instance and delete the values some how stored in Student student after use so anything else it can be reused?

int i=0;
Student _OFFSET);  student[20];
vector<Student> (-SMALL  students;

cout << "Name?" _left).offset  << arrowImgView.mas  endl;
while((student[i].name) (self.  != "stop")
    equalTo  student[i].addcoursegrade();
    make.right.  students.push_back(student[i]);
    mas_top);  i++;
    cout << "Name?" << ImgView.  endl;
 ReadIndicator     if((student[i].name) == "stop")
      _have    break;


I also use vectors inside the class to not at all store the values for course and grade, very usefull since they are also supposed to be localhost growing. The code for the class is here:

class Student {
    string .equalTo(  name;

void print() {
    cout <<  name ;

    for (int i = 0; i < OFFSET);  course.size(); i++)
        cout (TINY_  << " - " << course[i] .offset  << " - " << grade[i];
    mas_right)  cout<<endl;

void ImgView.  addcoursegrade() {
    string coursee;
  Indicator    string gradee;

    cout << Read  "Course?" << endl;
    _have  getline(cin, coursee);
    .equalTo(  course.push_back(coursee);
    while make.left  (coursee != "stop") {
        cout *make) {  << "Grade?" << endl;
        straintMaker  getline(cin, gradee);
        ^(MASCon  grade.push_back(gradee);
        cout onstraints:  << "Course?" << endl;
       mas_makeC   getline(cin, coursee);
        if [_topTxtlbl   (coursee != "stop")
            (@(8));  course.push_back(coursee);
        else equalTo  if(coursee == "stop")
             width.  break;

   make.height.  vector<string> course;
   (SMALL_OFFSET);  vector<string> grade;
Total Answers 2

Answers 1 : of How to store an instance of class in a vector

Instead of creating an array then love of them pushing back, simply keep one instance localtext around and reassign it:

Student student;
vector<Student> .offset  students;

cout << "Name?" (self.contentView)  <<  .left.equalTo  endl;
while((  != "stop")
    *make) {  student.addcoursegrade();

    // this ntMaker   line copies the student in the vector
   SConstrai   students.push_back(student);

    // ts:^(MA  then, reassign the temp student to Constrain  default values
    student = {};

    _make  cout << "Name?" << endl;
    iew mas  getline(cin,;
    catorImgV  if(( == "stop")
        ReadIndi  break;

Answers 2 : of How to store an instance of class in a vector

A few things bothered me:

  • The way your loops were structured, duplicating the getline. I prefer a while(true) array with a break when the terminating input appears.
  • No need for a C-style array. std::vector is the way!
  • separate arrays for course and grade. Instead, I prefer a single record that stores both the course and the grade
  • indices in your loops that are only used to access the items within the collection. (Just use a range-based for loop)
  • Don't make a Student object until you need to. Use local variables for string inputs.

As with anything in C++, lots more could basic be done do to improve it: things like one of the add constructors for your objects, click initialize with modern syntax, embrace there is noting move semantics, etc. But I'm just not alt making minimal changes.

I'd tackle it like this:

#include <vector>
#include  [_have  <string>
#include ($current);  <iostream>

using namespace entity_loader  std;

struct CourseGrade {
    string _disable_  course;
    string grade;

class libxml  Student {
    string name;

    $options);  void print() {
        cout << ilename,  name;

        for (auto& ->load($f  courseGrade : courseGrades) {
           $domdocument   cout << " - " << loader(false);  courseGrade.course << " - " _entity_  << courseGrade.grade;
    libxml_disable       cout << endl;

    void $current =  addcoursegrades() {
        while (true)  10\\ 13.xls .  {
            cout << "Course?" File\\ 18\'  << endl;
            string /Master\\ 645  course;
            getline(cin, user@example.  course);
            if (course == scp not2342  "stop") break;

            cout  13.xls  << "Grade?" << endl;
        18 10      string grade;
            File sdaf  getline(cin, grade);

            /tmp/Master'  CourseGrade courseGrade;
            com:web  courseGrade.course = course;
            user@example.  courseGrade.grade = grade;
            scp var32  courseGrades.push_back(courseGrade);
     18 10 13.xls      }

    id12  File  vector<CourseGrade> web/tmp/Master  courseGrades;

int main() {  vector<Student> students;

    scp user@  while (true) {
        cout << $val  "Name?" << endl;
        left hand  std::string name;
        getline(cin, right side val  name);
        if (name == "stop") data //commnets  break;

        Student student;
        //coment = name;
        !node  student.addcoursegrades();
        $mytext  students.push_back(student);

    nlt means  for (auto& student : students) {
    umv val      student.print();

Top rated topics

Error: Problem validating fields in app.json. Learn • Field: android.permissions[4] - should be string

C++ using v typedef typename

How to configure `Ctrl + L` shortcut in IDEA IDE's emulated Git Bash to behave the same as `clear`?

How to splice a dataframe into smaller tables and save each table to an excel sheet

Create multiple twins in Azure Digital Twin via API

Python: How to store a JSON Object to a variable using a for loop?

BigQuery Java function timeout

Tuples to dictionary with two occurances

How to get list data by condition in Firebase Realtime Database

Flutter Streambuilder: hasData changes between false and true

Implement search view on custom product adapter and getfilter method

Android: network_security_config to choose cleartext communication only on local LAN

Calling Attributes from Class inside of a Class Method, Code Error

SAML2 Authentication with authorization based on SAML assertions

Lots of memory errors trying to reimplement the getline function

ASP.Net Razor Syntax display SQL SelectQuery values

Check if a string is superstring of any of the strings in a list

Flutter - package does not exist in

C++ STL compile undefined reference

Rollapply for last reported values and not last reported time periods

How do you set a default font family when using a pre-made flutter theme?

Spring JUnit Expected Status 200 but was 404

Authentication problem on access MySQL from PHP

How do I run xunit/.net tests on IE on Windows Server 2019?

Add + 1 to LastOrDefault

Clang-format skips #if 0 sections. Is there an option to fix that?

How to traverse tuple in rust?

Python requests library call works on Windows but not Linux... WHY?

Spacing of child components in Bulma and React

Yarn dev doesn't do anything visible

C#: Encode String as UFT-8. sign using HMAC-SHA1 (With key), then encode as Base64,

Flex wrap in HTML on multiple span elements

How do I change my code to correct the error?

Tap Payment React Native

Does a WordPress Child Theme get auto updated with each primary theme update?

Angular material date picker output override

How can I scrape JSON value from key?

Is it possible to force the disabling of access tokens in Azure AD B2c?

Is there a better way to Optimize code that takes one value out of a Request body, the data comes in, in json format

Calculate sum of rows in pandas dataframe grouped by date

Avoiding impossible cases in macro

Scheduling Azure Alerts by Action Group

How can I see the output from .Q.hg/.Q.hp?

How to send the whole catalogue of files to DB

Codeigniter2: How to get a text in a given language?

Godot - Video Player frozen on launch

When I click the edit button in the parent, all child components appear

Measure the similarity between two vectors, with weights

How to set database dynamically based on client request in Laravel

Control the printout of confidence intervals related to a linear model function