我是C++的新手,所以这可能是一个非常简单的问题,但我无法在网上找到任何有帮助的例子.
我已经定义了自己的Bubble类,我需要创建一个vector/ list(我已经习惯了C#和Java,所以我不确定哪个是正确的)来动态存储Bubble对象.这是我的代码到目前为止:
#include "Bubble.h"
#include <vector>
#include <list>
int backgroundImages[10];
list<Bubble> bubbles;
vector<Bubble> bubbles_two;
Bubble b;
void AppMain()
{
loadImages();
ViewAdd(backgroundImages[8], 0,0);
b = Bubble();
b.velocity = Vector2D(9,4);
//I know this can't be right..
bubbles.add(b);
bubbles_two.add(b);
}
Run Code Online (Sandbox Code Playgroud)
既不是list也不是vector作品 - 它在我的错误列表中说"list/vector不是模板".
我应该使用哪个,list或者vector?我该如何正确实现它?
函数vector.add()和list.add()不存在.
#include "Bubble.h"
#include <vector>
#include <list>
int backgroundImages[10];
std::list<Bubble> bubbles(); // use the std namespace and instantiate it
std::vector<Bubble> bubbles_two(); // same here
Bubble b;
void AppMain()
{
loadImages();
ViewAdd(backgroundImages[8], 0,0);
b = Bubble();
b.velocity = Vector2D(9,4);
//I know this can't be right..
bubbles.push_back(b); // std::list also defines the method push_front
bubbles_two.push_back(b);
}
Run Code Online (Sandbox Code Playgroud)
向量和列表之间几乎没有明显的差异,但在功能上,有.
与其他基本标准序列容器(deques和lists)相比,向量通常是访问元素以及从序列末尾添加或删除元素的最有效时间.对于涉及在末尾以外的位置插入或删除元素的操作,它们比deques和list表现更差,并且与列表相比具有更少的一致迭代器和引用.
与其他基本标准序列容器(向量和deques)相比,列表在容器内的任何位置插入,提取和移动元素时通常表现更好,因此也在大量使用这些元素的算法中执行,例如排序算法.