我已从文件中读取数据,并希望将数据存储为对象向量。
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
如何将每条记录存储在向量中,然后访问数据?
我也尝试这样做:thingVector.push_back(Thing(v1, v2, v3, v4));
当我像这样尝试时,for语句中没有最后一行和倒数第三行,但我无法访问数据,因此放弃了这种方法。
有什么建议么?
东西.H文件
#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
东西.CPP文件
#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;
}