为什么使用push_back

时间:2019-05-07 00:27:23

标签: c++ vector

当我问为什么向量删除对象时,我并不是指向量中通过添加元素超出容量的行为的机制。我知道,一旦向量达到容量,将删除最初分配的内存,然后分配新的更大的内存以容纳数量增加的元素。对于类对象的向量,这意味着将调用析构函数。

我想知道的是,为什么当我尝试访问类的成员时,在通过push_back()超出类对象向量的容量之后,却出现错误“读取字符串的错误”。

我尝试将push_back更改为emplace_back(),但这没有帮助。我通过声明一个特定大小的向量并使用at()来赋值来使其工作,但那时候为什么我什至都使用向量开头?

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <utility>
#include "Book.h"
using namespace std;

int main () {
    string holder[5]; //used to hold strings from file.
    int temp; //Used to hold number from file.
    ifstream infile;

    vector<pair<Book, int>> bookInfo;

    infile.open(bookDatabase.txt)
    //i < 8 because the vector needs to start off holding 8 book objects.
    for (int i = 0; i < 8; i++) {
        //Second for loop designed based on specific format of the file.
        for (int j = 0; j < 5; j++) 
            getline(infile, holder[j]);
        infile >> temp;
        infile.ignore() //ignore newline;

        //Call class constructor for 5 string inputs.
        Book tempBook(holder[0], holder[1], holder[2], holder[3], holder[4]);

        //Here is where, in the debugger, I see that the string members of my 
        //book class all read "error reading characters of string"
        bookInfo.push_back(make_pair(tempBook, temp));

        //Read in empty line that separates information from book to book. 
        string tempString;
        getline(infile, tempString);
    }
    infile.close();

    return 0;
}


“我的书”对象仅具有字符串成员以及基本的getter和setter函数以及打印书的基本信息的函数。它没有指针成员,并且运行良好。

我也可以确定配对和文件输入的创建正确完成了。

我想知道的是为什么当我超出向量容量时会丢失我的书本对象。我被允许创建一个类对象的向量,那么为什么当容量超出容量需要将向量移动到更大的内存时,为什么没有一种机制可以保留对象的内容呢?还是我做错了什么?

1 个答案:

答案 0 :(得分:0)

我想通了,为了后代,我将发布我的发现。我向那些试图帮助我不要将代码发布到书本上的出色灵魂致歉,但是我现在已经可以发布代码了。

我不确定是什么导致我的程序在其他地方混乱,但是我的向量问题只是让我感到困惑。从我的角度来看,调试器的行为很奇怪,因此我认为有些错误,但是“从字符串读取字符时出错”是来自已删除的旧内存。成员已成功复制到__that对象(不确定对象是否正确),并再次解决该问题后,我的向量才按预期正确工作。

相关问题