[英]How to save collections of objects and use them in c++ vector
I need to use a vector that has a type of MyClass. 我需要使用具有MyClass类型的向量。
vector<MyClass> vMyClass;
vMyClass.Push_Back(new MyClass);
This does not seem to work for me. 这似乎对我不起作用。 What is going wrong?
怎么了? I am trying to simulate a List like in C#.
我正在尝试模拟C#中的列表。
I then need to perform an action on all items in the list. 然后,我需要对列表中的所有项目执行操作。 Like in C# foreach item in vMyClass.
就像在vMyClass中的C#foreach项目中一样。
I have looked everywhere for a simple example of this and have had no luck. 我到处都在寻找一个简单的例子,但没有运气。 Please help.
请帮忙。
new MyClass
returns a pointer to a MyClass
, but your vector contains objects, not pointers. new MyClass
返回一个指向MyClass
,但你的载体包含的对象,不是指针。
Try 尝试
vMyClass.push_back(MyClass());
or, if you need dynamic memory 或者,如果您需要动态内存
vector<MyClass*> vMyClass;
with your version. 与您的版本。 Note the all-lower-case
push_back
. 注意所有小写的
push_back
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.