首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >运行时已知的2d大小数组的列表(或向量)的声明

运行时已知的2d大小数组的列表(或向量)的声明
EN

Stack Overflow用户
提问于 2013-11-01 14:19:51
回答 2查看 7.9K关注 0票数 1

我有许多2D数组,只有在运行时才知道大小。

代码语言:javascript
运行
复制
  int arr1[i][k];
  int arr2[i][k];
  ...

实际上,它们是在for循环中创建的。在循环结束时,我需要它们都在记忆中:

代码语言:javascript
运行
复制
   list<????> mylist;
   mylist.push_back(arr1);
   mylist.push_back(arr2);

如何将它们推入std::vector std::list?我看到的所有示例都需要事先知道数组的大小。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-01 14:25:41

使用可复制和可分配的内容,如std::vector。您可以编写自己的2D类,包装单个向量(这将是首选选项),也可以使用向量向量。例如(未经测试):

代码语言:javascript
运行
复制
class Array2D
{
 public:
  Array2D(int rows, int cols) : cols_(cols), data(rows*cols) {}
  int& operator()(int i, int j) { return data_[i*cols_ + j]; }
  const int& operator()(int i, int j) const { return data_[i*cols_ + j]; }
  // to-do: add an efficient, exception safe swap method.
 private:
  unsigned int cols_;
  std::vector<int> data_;
};

Array2D arr1(i, j);
Array2D arr2(i, j);
std::list<Array2D> mylist;

代码语言:javascript
运行
复制
std::vector<std::vector<int>> arr1(i, std::vector<int>(k));
std::list<std::vector<std::vector<int>>> mylist;
票数 0
EN

Stack Overflow用户

发布于 2015-08-28 10:57:34

对于2d数组声明,可以使用映射。

代码语言:javascript
运行
复制
std::maps<int,int> Array2D;
loop{
    scanf("%d %d",&a,&b);
    Array2D[a]=b;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19728613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档