为什么我的代码没有将每个对象都添加到向量中?

时间:2019-04-08 04:23:13

标签: c++ object vector

我正在从文件中读取信息,并希望将收到的信息解析为数据并将其存储到相应的对象中,然后将这些对象推回向量中。但是,当代码将信息存储到对象中然后又推回向量中时,向量将不保存该值。然后,它会跳过向量中的几个位置,并开始在文件末尾正确添加对象。有没有办法确保所有元素都会被填充?

这是我的结构:

struct Address{ 
        string streetAddress; 
        string city; 
        string state; 
        string zipCode; 
};

struct Customer { 
        string customerNum; 
        string customerName; 
        double lineOfCredit; 
        Address * corperateAddress; 
};

如您所见,Customer的成员是一个指向Address结构的指针。

以下是该函数和一些变量用于以下代码:

void readData(vector<Customer>&addCust, vector<Address>&cAdd, vector<Product>&pAdd){

Address street;
Customer add;
Product product;

vector<string> custInfo;
vector<string> custAddress;
vector<string> custProduct;
ifstream file,stock;

这是发生错误的地方,我相信它在if-else语句内:

        custAddress=parse(location,',');                   //Parse the location to go into Address struct
        check = linearSearchAddress(cAdd,custAddress[0]);  //Checks Address vector to see if there is the same location

        street.streetAddress=custAddress[0];               //Adds 1st parse to the Struct member 
        street.city=custAddress[1];                        //Adds 2nd parse to the Struct member 
        street.state=custAddress[2];                       //Adds 3rd parse to the Struct member 
        street.zipCode=custAddress[3];                     //Adds 4th parse to the Struct member

        if(check==-1){                                     //If address is not found then add it to the Address vector 
            cAdd.push_back(street);                        //Adding objects into the Address vector
            add.corperateAddress = &cAdd.back();
        } else {
            add.corperateAddress=&cAdd[check];             //Adds location that is within vector already 
        }
         addCust.push_back(add);                           //Adding objects into Customer vector
     }
        cout<<addCust[0].corperateAddress->streetAddress<<endl;  // Element is empty some how ?

1 个答案:

答案 0 :(得分:3)

push_back上调用vector时,如果它导致向量的大小增加,则会使向量中的所有指针和引用无效。 vector将所有对象存储在一个连续的内存块中,因此,当它增大大小时,可能需要分配一个新的内存块,从而使向量中所有现有的对象都移到该新位置。

您在vector中存储指向对象的指针的模式不是一个好方法,尽管您可以通过从一开始就在vector中保留足够的空间来使其工作-如果您知道有多大的空间这将是。否则,您可以使用vector之外的其他不具有此属性的集合。