为什么我的代码没有将每个对象添加到向量中
Why does my code not add every object into the vector?
我正在从文件中读取,并且使用我收到的信息,我想解析数据并将它们存储到它们相关的对象中,然后将其推回向量中。但是,当代码将信息存储到对象中,然后被推回向量时,向量不会保存该值。然后,它会跳过矢量中的几个位置,并开始在文件末尾正确添加对象。有没有办法确保所有元素都被填充?
这是我的结构:
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
以外的某些集合。
相关文章:
- 队列未添加对象-C++11
- 创建/向容器添加对象时如何使用构造函数/析构函数
- 向 std::map 添加对象和自定义比较<>
- 如何在构造函数的静态列表中添加对象
- C++ std::vector 创建对象然后添加对象与在向量中创建对象之间的区别?
- 重载 + 运算符以使用 int 添加对象
- 如何在数组中添加对象成员
- 为什么类对象的向量在使用push_back添加对象时会删除对象
- 我如何阻止在多个向量中添加对象
- 指针集合和添加对象
- 动态添加对象
- 在c++中向向量添加对象vs向向量添加指针
- 添加c++对象到Objective C集合(NSSet)的麻烦
- 添加对象指针到链表c++
- c++ push_back只向vector中的位置0添加对象
- 在TStringList中添加对象
- 在c++中似乎不能正确地向数组中添加对象
- 使用push_back向vector添加对象工作正常,但使用访问器语法[]添加对象不工作
- 在for循环中向vector中添加对象
- 使用CMake从二进制文件编译并添加对象文件