如何使用指针用对象填充向量 [英] how to fill a vector with objects using pointers

查看:158
本文介绍了如何使用指针用对象填充向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个赋值,我必须创建一个向量并用对象填充它。我发现这个代码:

I have an assignment where I have to create a vector and fill it with objects. I found this code:

Vehicle * v = NULL;
vector<Vehicle*> *highway;
highway = new vector<Vehicle*>;

我理解第一行创建一个名为 v 为空并指向对象 Vehicle

I understand the first line where it creates a pointer named v that is empty and points at the object Vehicle.

你能解释一下其他两行如何工作,为什么在创建向量时使用指针?

Can you please explain to me how the other 2 lines work and why is it using pointers when creating the vector?

推荐答案

以下是逐行简要说明:

Vehicle * v = NULL;

定义 v 类型的指针 Vehicle 并将其初始化为 NULL

define a pointer v of type Vehicle and initialize it to NULL.

vector<Vehicle*> *highway;

定义高速公路 c $ c> vector< Vehicle *> 。

define a pointer highway of type vector<Vehicle*>.

highway = new vector<Vehicle*>;

动态分配向量< Vehicle *> 并将其分配给向量 highway

dynamically allocate vector<Vehicle*> and assign it to vector highway.

请查看 std :: vector ,并确保你明白为什么最后两行没有什么意义。

Have a look at std::vector and make sure you understand why the last two lines doesn't make much sense.


如何使用指针填充一个向量?

How to fill a vector with objects using pointers?

要填充动态分配的向量,您可以写成:

To fill the dynamically allocated vector, you could write:

highway->push_back(Vehicle_Element);    

这篇关于如何使用指针用对象填充向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆