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

Why does my code not add every object into the vector?

本文关键字:添加 对象 向量 代码 我的 为什么      更新时间:2023-10-16

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

这是我的结构:

struct Address{ 
        string streetAddress; 
        string city; 
        string state; 
        string zipCode; 
};
struct Customer { 
        string customerNum; 
        string customerName; 
        double lineOfCredit; 
        Address * corperateAddress; 
};

如您所见,客户成员是指向地址结构的指针。

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

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 ?

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

vector中存储指向对象的指针的模式并不好,尽管您可以通过从一开始就在vector中保留足够的空间来使其工作 - 如果您知道它会有多大的话。否则,可以使用除没有此属性的vector以外的某些集合。