使用vector和结构体定义静态链表 c++
时间: 2023-11-30 09:43:07 浏览: 36
以下是使用vector和结构体定义静态链表的C++代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct Node {
int data;
int next;
};
int main() {
vector<Node> list(100); // 定义一个大小为100的vector,存储静态链表
int head = 0; // 头指针
int n = 5; // 静态链表长度
// 初始化静态链表
for (int i = 0; i < n; i++) {
list[i].data = i + 1;
list[i].next = i + 1;
}
list[n - 1].next = -1; // 最后一个结点的next指针指向-1,表示链表结束
// 遍历静态链表
int p = head;
while (p != -1) {
cout << list[p].data << " ";
p = list[p].next;
}
cout << endl;
return 0;
}
```
相关问题
使用vector和结构体定义静态链表 c++且vector不初始化大小
使用vector和结构体可以定义静态链表,具体实现如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct Node {
int val;
int next;
};
int main() {
vector<Node> list;
list.push_back({1, 2});
list.push_back({2, 3});
list.push_back({3, -1});
for (int i = 0; i < list.size(); i++) {
cout << list[i].val << " " << list[i].next << endl;
}
return 0;
}
```
上述代码中,我们定义了一个结构体Node,包含两个成员变量val和next,分别表示节点的值和下一个节点的下标。然后我们使用vector来存储这些节点,vector的大小会根据我们push_back的元素数量自动调整。最后我们遍历vector,输出每个节点的值和下一个节点的下标。
如果不想初始化vector的大小,可以直接使用默认构造函数创建一个空的vector,然后通过push_back方法添加元素。具体实现如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct Node {
int val;
int next;
};
int main() {
vector<Node> list;
list.push_back({1, 2});
list.push_back({2, 3});
list.push_back({3, -1});
for (int i = 0; i < list.size(); i++) {
cout << list[i].val << " " << list[i].next << endl;
}
return 0;
}
```
上述代码中,我们创建了一个空的vector,然后通过push_back方法添加元素。
vector和结构体一起使用
当使用结构体和向量(vector)一起使用时,可以将结构体作为向量的元素类型。这样做可以方便地存储和操作多个结构体对象。
首先,定义一个结构体类型,例如:
```cpp
struct Person {
std::string name;
int age;
};
```
然后,可以创建一个包含该结构体类型的向量:
```cpp
std::vector<Person> people;
```
接下来,可以向向量中添加结构体对象:
```cpp
Person p1 = {"Alice", 25};
Person p2 = {"Bob", 30};
people.push_back(p1);
people.push_back(p2);
```
还可以通过索引访问和修改向量中的结构体对象:
```cpp
std::cout << people[0].name << std::endl; // 输出 "Alice"
people[1].age = 35;
```
当然,你也可以使用迭代器遍历向量中的结构体对象:
```cpp
for (const auto& person : people) {
std::cout << person.name << ", " << person.age << std::endl;
}
```
这样,就可以在向量中存储和操作多个结构体对象了。希望能帮到你!