I have read in data from a file and want to store the data as a vector of objects.
vector <Thing*> thingVector;
for (int i = 0; i < 10; i++) {
// Read in contents of file
getline(fileName, v1, ',');
cout << v1 << endl;
getline(fileName, v1, ',');
cout << v2 << endl;
getline(fileName, v3, ',');
cout << v3 << endl;
getline(fileName, v4, '\n');
cout << v4 << endl << endl;
// Store
Thing* thingDetails = new Thing(v1, v2, v3, v4);
thingVector.push_back(thingDetails);
delete thingDetails;
}
thingFile.close();
cout << "Size of THING vector is " << thingVector.size() << endl; // Displays 10
cout << thingVector[0].getV1 << endl; // ERROR HERE
How can I store each record in the vector and then access the data?
I also tried to do it like this:
thingVector.push_back(Thing(v1, v2, v3, v4));
I didn’t have the last and third to last lines in the for statement when I tried it like this, but I couldn’t access the data so gave up on this method.
Any suggestions?
THING .H FILE
#ifndef THING_H
#define THING_H
#include <string>
using namespace std;
class Thing {
public:
Thing(string v1, string v2, string v3, string v4);
string getV1();
string getV2();
string getV3();
string getV4();
private:
string v1;
string v2;
string v3;
string v4;
};
#endif
THING .CPP FILE
#include "thing.h"
#include <string>
using namespace std;
Thing::Thing(string aV1, string aV2, string aV3, string aV4) {
v1 = aV1;
v2 = aV2;
v3 = aV3;
v4 = aV4;
}
string Thing::getV1(){
return v1;
}
string Thing::getV3(){
return v2;
}
string Thing::getV3){
return v3;
}
string Thing::getV4(){
return v4;
}
You should use
This will pass object rather than the pointer.
Also