I have a question regarding iterating over a vector that holds objects. For some reason, the code within the for loop is not printing to the console. Does anyone know why?
I've included the header and class files for the object I've made as well. If there are any other comments regarding the use of methods, design, etc.. please feel free to comment. Constructive criticism is always welcome!
#include <iostream>
#include <Doctor.h>
#include <vector>
usingnamespace std;
int main()
{
string name = "Bob";
Doctor doc1 (name);
Doctor doc2;
cout << "doc1 name: " + doc1.getName() << endl;
cout << "doc2 name: " + doc2.getName() << endl;
doc1.setID(2019);
doc2.setName("Alice");
doc2.setID(2020);
// My attempt to use a vector of objects.
std::vector<Doctor> docList;
std::vector<Doctor>::iterator iter;
// Is this the correct way to insert objects into the vector?
docList.insert(iter, doc2);
docList.insert(iter, doc1);
/* For some reason, the name of each Doctor object is not printing
* in the for loop below */
for( int i = 0; i < docList.size(); i++){
string name = docList[i].getName();
cout << name << endl;
}
return 0;
} // end main
#ifndef DOCTOR_H
#define DOCTOR_H
#include <string>
class Doctor
{
private:
std::string name;
int id;
public:
Doctor();
Doctor (std::string n);
Doctor (std::string n, int num);
//virtual ~Doctor();
std::string getName(){return name;}
void setName(std::string);
int getID(){return id;}
void setID(int num);
};
#endif // DOCTOR_H
// Beginning doctor.cpp file below:
#include "Doctor.h"
usingnamespace std;
/*
This is the Doctor cpp file where the Doctor class's
functions are implemented.
*/
string name;
int id;
Doctor::Doctor()
{
name = "BLANK NAME";
id = 99999;
}
Doctor::Doctor(string n)
{
name = n;
}
Doctor::Doctor(string n, int fig)
{
name = n;
id = fig;
}
/*Doctor::~Doctor()
{
//dtor
}*/
string getName(){ return name;}
void Doctor::setName(string n){ name = n;}
int getID() {return id;}
void Doctor::setID(int fig){ id = fig;}
// end of Doctor.cpp
has two problems:
a.) iter is not initialized to refer to a particular position within the vector; and
b.) insert makes all existing iterators invalid (in general).