gpt4 book ai didi

c++ - 如何在 C++ 中创建类对象的 vector ?

转载 作者:太空狗 更新时间:2023-10-29 23:21:17 26 4
gpt4 key购买 nike

我正在尝试使用 C++ 中的 vector 创建一个简单的堆栈。

代码如下:

#include <vector>

class Site
{
public:
int i; // site position i (x-axis)
int s; // site state
vector<Site> neighbors;
Site(void);
Site(int ii, int ss);
void AddNeighbor(Site &site);
};
Site::Site()
{
i = -1;
s = -1;
vector<Site> neighbors;
}
Site::Site(int ii, int ss)
{
i = ii;
s = ss;
}
void Site::AddNeighbor(Site &site)
{
neighbors.push_back(site);
}

void testStack()
{
int tot = 600;
vector<Site> myStack();
int i = 0;
while (i < tot)
{
Site site(i, 1);
myStack.push_back(site);
i++;
}

i = 0;
while (i < tot)
{
Site *site = myStack.back();
myStack.pop_back();
cout << site->i << site->s << endl;
i++;
}
}

编译器错误:

ising_wolff.cpp: In function ‘void testStack()’: ising_wolff.cpp:373:17: error: request for member ‘push_back’ in ‘myStack’, which is of non-class type ‘std::vector()’ myStack.push_back(site); ^ ising_wolff.cpp:380:30: error: request for member ‘back’ in ‘myStack’, which is of non-class type ‘std::vector()’ Site *site = myStack.back(); ^ ising_wolff.cpp:381:17: error: request for member ‘pop_back’ in ‘myStack’, which is of non-class type ‘std::vector()’ myStack.pop_back();

这些错误是什么意思?

以下是我浏览过的一些网站:

1) Creating objects while adding them into vectors

2) push_back causing errors in C

3) how to create vectors of class object

最佳答案

如何在 C++ 中创建类对象的 vector ?

从更简单的事情开始,这样您就可以掌握它。

首先,创建一个原始整数 vector :

#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> sites(5);
sites.push_back(5);
for(int x = 0; x < sites.size(); x++){
cout << sites[x];
}
cout << endl;
return 0;
}

编译它:

g++ -o test test.cpp

运行它:

./test
000005

以与上述类似的方式创建类对象的 vector :

#include <iostream>
#include <vector>
using namespace std;

class Site {
public:
int i;
};

int main() {
vector<Site> listofsites;
Site *s1 = new Site;
s1->i = 7;
Site *s2 = new Site;
s2->i = 9;
listofsites.push_back(*s1);
listofsites.push_back(*s2);
vector<Site>::iterator it;
for (it = listofsites.begin(); it != listofsites.end(); ++it) {
cout << it->i;
}
return 0;
}

应该打印:

79

关于c++ - 如何在 C++ 中创建类对象的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21919277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com