向量中的结构

Struct within vector

本文关键字:结构 向量      更新时间:2023-10-16

我对 c++ 很陌生,所以请耐心等待。 我有一个由结构组成的向量。他们都在一个班级里。我应该从文件中读取数据(工作正常)并保存。但是当我尝试在结构的任何部分输入信息时,我的程序崩溃了。

这是在标头中的类中:

class Content{
private:
string discName;
string discID;
struct content{
int number=1;
string name;
string type;
int size;
int track;
int sect;
}heck;
vector <content> block;
public:
Content();
void read_int(fstream& file);
void read_id(fstream& file);
void read_string(fstream&, int, string);
void read_type(fstream& file);
};

这是它使用的功能之一:

void Content::read_int(fstream& file){
int file_content;
file.read(reinterpret_cast<char*> (&file_content), 1);
this->block[0].track=file_content;
}

根据我的发现,大多数人倾向于以相反的方式进行,在结构中使用向量,这样更好吗?

两种可能性(至少):

首先,向量已经包含要设置的元素,并从文件中读取值,然后您需要确保向量已经包含元素。也许在Content的构造函数中?类似于block.resize(n),对于一些适当的n.

其次,向量最初不包含任何元素,您希望使用从文件读取的数据创建的元素填充它。像这样:

file.read(reinterpret_cast<char*> (&file_content), sizeof file_content); // read data from file
content c; // construct an element
c.track = file_content; // set data of the element
this->block.push_back( c ); // add that new element to the vector

读取文件时请注意提供适当的大小。似乎您尝试读取 int,因此要读取的字节数应该是存储 int:sizeof int的字节数。

另请注意,您对Content的定义包含一个名为heck...我怀疑你需要什么。我怀疑struct content只是向量中包含的类型的定义,因此以下内容更好:

struct content {
int number=1;
string name;
string type;
int size;
int track;
int sect;
};
class Content{
private:
string discName;
string discID;
vector <content> block;
public:
Content();
void read_int(fstream& file);
void read_id(fstream& file);
void read_string(fstream&, int, string);
void read_type(fstream& file);
};

请注意,类型标识符的首字母应大写。那么你可能有:

struct ContentData {
....
};
class Content {
....
vector<ContentData> block;
};

或类似。

更好的选择是使用单个函数来读取返回 int 的 int,并且您正确使用:

void Content::read_int(fstream& file){
int file_content;
file.read(&file_content, sizeof file_content); // take care of returned value!!!
return file_content;
}
Content c;
c.track = read_int(f);
c.size = read_int(f);
c.type = read_string(f);
c.name = read_string(f);
...
bloc.push_back( c );

正如评论所建议的那样,您的程序可能会崩溃,因为块中没有元素,因此块[0]会导致未定义的巴哈维。如果您使用的是 C++11 标准并希望在向量中为每个读取值添加新元素,请尝试 std::vector::emplace_back()。或者,如果您出于某种原因希望它始终排在第一位,请在构造函数中初始化它或在函数中使用它:

void Content::read_int(fstream& file)
{
int file_content = file.get(); //no need for reintepret casting ;)
if (!block.empty())
this->block[0].track=file_content;
//possibly else to create the element if needed
}

为了解决你的第二个问题,在这个例子中没有"大多数人倾向于"或"更好的方法"这样的东西。这是你想要实现的目标的问题。结构中的向量与保存结构体的向量不同。
在这里,你有一个保存元素的数组,其中每个元素包含 4 个整数和 2 个字符串。如果你想在你的结构中创建向量,你将为每个 instace 提供一个结构,包含 4 个整数、2 个字符串和一个向量。