c++ - 从对象 vector 访问数据

标签 c++

我已从文件中读取数据,并希望将数据存储为对象 vector 。

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

如何将每条记录存储在 vector 中,然后访问数据?

我也试过这样做: thingVector.push_back(事物(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;
}

最佳答案

您的问题是您正在存储指向 Thing 的指针,但正在删除指针。所以 vector 最终充满了悬空指针。您可以通过简单地使用 Things vector 来避免所有这些麻烦:

vector <Thing> thingVector;
...
thingVector.push_back(Thing(v1,v2,v3,v4));

然后你可以像这样访问它:

std::string s = thingVector[0].getV1();

cout << thingVector[0].getV1() << endl;

除非绝对必要,否则您不应使用动态分配对象的指针,并且在您的代码示例中似乎没有理由这样做。如果这样做,请考虑使用 smart pointers处理内存管理。

请注意,如果您选择了 Thing 指针或智能指针的 vector,那么您必须使用 -> 调用每个元素的方法 运算符:

cout << thingVector[0]->getV1() << endl;
                  //   ^ here!

顺便说一句,你真的应该避免using namespace std;,特别是在头文件中。

关于c++ - 从对象 vector 访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12235869/

相关文章:

c++ - 为什么在这里使用 static_cast 而不是 reinterpret_cast 很重要?

C++ vector 错误(Visual C++ 2008 Express Edition)

c++ - 根据另一个对象的值对类中的二维对象进行排序并赋值 C++

c++ - Boost::graph 获取到根的路径

c++ - 按顺序复制二叉树

c++ - 使用spdlog(C++)进行记录,记录器未将日志写入文件

c++ - 在同一语句中调用的 IO 执行函数 : Undefined or unspecified?

c++ - 在CMake中使用find_package时,是否会显式包含 header ?

c++ - 在 C++ 中运行用于输出的辅助线程

c++ - SVM + HOG,发现对象总是NULL