gpt4 book ai didi

c++ - 处理二维 vector C++

转载 作者:行者123 更新时间:2023-11-30 03:03:26 24 4
gpt4 key购买 nike

我需要在 C++ 中设置和访问二维结构 vector 。我的结构定义为:

struct nodo{
int last_prod;
int last_slot;
float Z_L;
float Z_U;
float g;
bool fathomed;
};

我将 vector 定义为:

vector<vector<struct nodo> > n_2;

现在,我需要创建 n_2 的几个元素,它们将再次成为 vector ,然后访问它们的单个成员。我怎样才能做到这一点?这是我到目前为止的一段代码:

for(int i=1;i<112;i++){
n_2.push_back(vector<struct nodo>(111-i));
for(int j=1;j<112-i;j++){
n_2[i][j].last_prod=j;
}
}

这是行不通的。

最佳答案

vector 的大小为 0,直到您告诉它调整大小,或者除非您使用特定大小对其进行初始化。在创建 vector 时传递 vector 的大小:

for(int i=1;i<112;i++){
n_2.push_back(vector<struct nodo>(112-i));
for(int j=1;j<112-i;j++){
n_2[i][j].last_prod=j;
}
}

此外,看起来您正在跳过第 0 个索引,这意味着您的数组中的第一个值将被跳过。这可能是不希望的。

最后,如果您的数组大小不变,请考虑使用 std::array而不是 std::vector。请注意,std::array 是一项 C++11 功能,可能不可用,具体取决于您的编译器。

如果我写这段代码,我可能会这样写:

#include <array>
using namespace std;

// allocate an array of 112 <struct nodo> arrays, each of size 112
array<array<struct nodo, 112>, 112> n_2;
for (int i = 0; i < 112; i++)
{
for (int j = 0; j < 112; j++)
{
n_2[i][j].last_prod = j;
}
}

或者,如果我没有支持 C++11 的编译器:

#include <vector>
using namespace std;

// allocate a vector of size 112 of <struct nodo> vectors, each of size 112
vector<vector<struct nodo> > n_2(112, vector<struct nodo>(112));
for (int i = 0; i < 112; i++)
{
for (int j = 0; j < 112; j++)
{
n_2[i][j].last_prod = j;
}
}

更理想的是,您应该使用一维 vector ,并将其简单地视为二维 vector 。这样,您可以一次完成一次内存分配,而不是 112 次较小的分配。这变得相当挑剔,但显然 O(1) 解决方案优于 O(n) 解决方案,后者在分配方面优于 O(n^2) 解决方案,因为分配速度很慢。

关于c++ - 处理二维 vector C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9365043/

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