C++ 列表/vector 帮助

标签 c++

我是 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);
}

listvector 都不起作用 - 它在我的错误列表中显示“list/vector is not a template”。

我应该使用哪个,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);
}

vector 和列表之间几乎没有明显的区别,但在功能上却有区别。

Compared to the other base standard sequence containers (deques and lists), vectors are generally the most efficient in time for accessing elements and to add or remove elements from the end of the sequence. For operations that involve inserting or removing elements at positions other than the end, they perform worse than deques and lists, and have less consistent iterators and references than lists.

Compared to other base standard sequence containers (vectors and deques), lists perform generally better in inserting, extracting and moving elements in any position within the container, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

关于C++ 列表/vector 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462623/

相关文章:

c++ - NSMutableDictionary 和 std::map 的访问运算符之间的区别

c++ - C++中的数据库程序问题

c++ - 使用可变参数模板展开序列范围

c++ - 类中 vector 的删除-删除习语问题

c++ - [c++]检查文件结尾

c++ - 在 Windows 上列出 *.lib 中的函数

c++ - QEvent::Close 不是由 changeEvent 触发的

c++ - 2D 钻石(等距) map 编辑器 - 无限扩展的纹理?

c++ - 我如何使用 C++ 执行此操作

c++ - XercesDOMParser 和 XIncludes