gpt4 book ai didi

c++ - 如何使用由 for 循环创建的 vector vector 构建链表?

转载 作者:行者123 更新时间:2023-11-28 01:21:18 31 4
gpt4 key购买 nike

我正在尝试将指针添加到我刚刚使用 vector 的 vector 创建的二维矩阵。我想使用的代码是用数组来实现的,但我想改为使用我刚刚创建的 vector 的 vector 。所以我的问题是:

  1. 这可能吗?
  2. 如果是这样,我需要在要使用的代码中更改什么?

下面是我创建 vector vector 的代码。 K 是 vector 代表的房间数,并且已经预先初始化。

    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++ 的新手,如果这是一个荒谬的问题,我深表歉意。

最佳答案

如果替换原型(prototype)就可以做到:

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[] 访问 vector 元素。

希望能解决您的问题。


编辑:

为了避免警告,你甚至可以这样写:

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;
}

我用更高效和可读性更高的 vector 初始化替换了您的代码。

希望对你有帮助:)

关于c++ - 如何使用由 for 循环创建的 vector vector 构建链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56146728/

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