如何使用由for循环创建的向量向量构建链接列表
How do I construct a linked list using a vector of vectors created by a for loop?
我正在尝试将指针添加到刚刚使用向量向量的2D矩阵中添加指针。我想使用的代码与数组一起使用,但我想使用刚创建的向量向量。所以我的问题是:
- 这是可能的吗?
- 如果是这样,我需要更改我要使用的代码?
以下是我创建向量向量的代码。k是向量代表的房间数量,并以前已初始化。
for (int i = 0; i < K; ++i) //a loop for each room
{
int M = 0; // initializing rows variable
int N = 0; // initializing columns variable
cin >> M >> N;
vector<vector<int> > matrix(M); //give a matrix with a dimension M*N with all elements set to 0
for (int i = 0; i < M; i++)
matrix[i].resize(N);
for (int i = 0; i < M; i++) //adding each row to the matrix
{
for (int j = 0; j < N; j++) //adding each column to the matrix
{
cin >> matrix[i][j]; //putting all the elements in the matrix
}
}
}
这是我想使用的代码,如果可能的话:https://www.geeksforgeeks.org/construct-linked-list-2d-matrix/
我在C 方面很新,所以如果这是一个荒谬的问题,我很抱歉。
如果您替换原型:
Node* construct(int arr[][3], int i, int j,
int m, int n)
{
//...
}
:
Node* construct(const vector<vector<int>> & arr, int i, int j,
int m, int n)
{
//...
}
这样,它应该起作用,因为您可以使用operator[]
访问向量元素。
我希望它可以解决您的问题。
编辑:
要避免警告,您甚至可以写:
Node* construct(const vector<vector<int>> & arr, size_t i, size_t j,
size_t m, size_t n)
{
//...
}
edit2:完整的示例代码
我完全使用了您在您的问题中给我们的代码:
// CPP program to construct a linked list
// from given 2D matrix
#include <bits/stdc++.h>
using namespace std;
// struct node of linked list
struct Node {
int data;
Node* right, *down;
};
// returns head pointer of linked list
// constructed from 2D matrix
Node* construct(const vector<vector<int>> & arr, size_t i, size_t j,
size_t m, size_t n)
{
// return if i or j is out of bounds
if (i > n - 1 || j > m - 1)
return nullptr;
// create a new node for current i and j
// and recursively allocate its down and
// right pointers
Node* temp = new Node();
temp->data = arr[i][j];
temp->right = construct(arr, i, j + 1, m, n);
temp->down = construct(arr, i + 1, j, m, n);
return temp;
}
// utility function for displaying
// linked list data
void display(Node* head)
{
// pointer to move right
Node* Rp;
// pointer to move down
Node* Dp = head;
// loop till node->down is not NULL
while (Dp) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp) {
cout << Rp->data << " ";
Rp = Rp->right;
}
cout << "n";
Dp = Dp->down;
}
}
// driver program
int main()
{
// 2D matrix
vector<vector<int>> arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
size_t m = 3, n = 3;
Node* head = construct(arr, 0, 0, m, n);
display(head);
return 0;
}
我用更高效,更可读的向量初始化替换了您的代码。
我希望它能帮助您:(
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何在提升间进程中构建具有给定计数的向量并向其添加元素
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 创建一个类来访问和指定向量类型,并构建一个获取位置并为其分配区域的类
- C++如何为向量向量构建迭代器
- 使用步骤c++构建一个向量
- 在编译时以增量方式构建变量指针的向量
- 如何通过向量构建数组
- 如何通过参考构建向量的子句法
- 如何使用由for循环创建的向量向量构建链接列表
- 如何使用向量字符串令牌构建表达树
- 如何从 2 个向量构建顶点矩阵?
- 如何使用opencv从矩阵向量中构建图像
- glm ::翻译 - 它是否从向量构建矩阵
- 使用PETSC库与向量构建稀疏矩阵
- Cgal::D ynamic_dimension_tag 在尝试构建点向量时出错
- 如何使用C++构建可以旋转的向量数组
- 包含从 mysql row[x] 构建的固定长度数组的向量
- 基于另一个向量构建的向量的成员的geting索引
- 如何从源向量构建搜索结果的向量<><>?