矢量中的结构

时间:2018-03-09 12:25:56

标签: c++

我对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;
}

从我发现的情况来看,大多数人倾向于以相反的方式做到这一点,在结构中使用向量,是否更好?

2 个答案:

答案 0 :(得分:1)

两种可能性(至少):

首先,向量已包含要使用从文件读取的值设置的元素,然后需要确保向量已包含元素。也许在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 );

答案 1 :(得分:0)

正如评论建议的那样,你编程可能崩溃,因为块中没有元素,所以block [0]会导致未定义的bahaviour。如果您使用的是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个int和2个字符串。如果你想在你的结构中创建向量,你就会为每个实例提供一个结构,包含4个整数,2个字符串和一个向量。

相关问题