C++列表/矢量帮助

C++ list/vector help

本文关键字:帮助 列表 C++      更新时间:2023-10-16

我是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?我该如何正确地实现它?

函数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);
}

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

与其他基本标准相比序列容器(deques和列表),矢量通常是最多的高效的访问时间元素,并添加或删除元素从序列的末尾开始。对于涉及插入或移除其他位置的元素他们的表现比deques和list,并且拥有更少一致迭代器和引用比列表多。

与其他基本标准相比序列容器(矢量和deques),列表通常执行在插入、提取和在容器,因此也在密集使用的算法这些,就像排序算法。

它们位于std命名空间中。就像C++标准库的所有部分一样。因此,它们被正确地称为std::liststd::vector

它们也没有名为add的成员函数。您可能需要查找一个C++引用。

Vector和list是std命名空间的一部分。所以你应该这样声明你的向量和你的列表:

std::list<Bubble> bubbles;
std::vector<Bubble> bubbles_two;

此外,添加元素的成员函数是push_back。

listvector位于std命名空间中,因此您必须在那里查找它们。

std::vector<Bubble> bubbles;

在任何一种情况下,都可以使用.push_back附加到容器中。如果有疑问,您通常应该更喜欢vector

此处缺少命名空间。list和vector都是标准名称空间的一部分,这意味着您可以通过在文件开头写入using namespace std;一次或在使用变量的每个位置写入std::liststd::vector来全局包含名称空间。

尝试

std::list<Bubble> bubbles;
std::vector<Bubble> bubbles_two;

列表和矢量在std命名空间中定义。

#include <iostream>  //Desouky//
using namespace std;
struct node
{
int data;
node* link= NULL;
};
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
node* head = new node;
node*temp = new node;
head = temp;
int x;
cin >> x;
temp->data = x;
while (cin >> x)
{
    node* temp1 = new node;
    temp1->data = x;
    temp->link = temp1;
    temp = temp->link;
}
temp = head;
while (temp != NULL)
{
    cout << temp->data << " ";
    temp = temp->link;
}
}