简体   繁体   English

在运行时将指针推到矢量C ++

[英]Push pointers to vector at runtime C++

My program will read input data that contains N lines. 我的程序将读取包含N行的输入数据。 Each line contains data that will be assigned to a single object. 每行包含将分配给单个对象的数据。 Since the number of objects required will be determined at runtime, I plan to allocate space for them on the heap. 由于所需的对象数将在运行时确定,因此我计划在堆上为其分配空间。

I want to include a vector of pointers to these objects. 我想包括一个指向这些对象的指针向量。 My first approach was to use a loop running N times, and allocate the space with, 我的第一种方法是使用运行N次的循环,并分配空间,

Customer* cust_i = new Customer

Then use customer_vector.push_back(cust_i) to populate the vector. 然后使用customer_vector.push_back(cust_i)填充矢量。

Seems clumsy, and given that I don't understand dynamic memory allocation in C++ all that well, I would appreciate any advice approaching this problem a better way. 似乎很笨拙,而且鉴于我不太了解C ++中的动态内存分配,因此,我希望您能以更好的方式解决此问题。

Thanks. 谢谢。

You don't actually need to store the pointers to Customer 您实际上不需要存储指向Customer的指针
Since vector is already a dynamic container you can do 由于vector已经是一个动态容器,您可以执行

std::vector<Customer> customer_vec;

// read file
// ...
// example assuming Customer has a constructor taking 2 strings
customer_vec.emplace_back( "foo", "bar" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM