在C ++中创建列表列表 [英] Creating list of lists in c++
问题描述
在C ++中,推荐的创建特定大小列表的方法是什么,其中列表的每个元素都是3个元素的列表?
In C++, what is the recommended way of creating a list of a certain size, where each element of the list is a list of 3 elements?
为澄清起见,在Python中我要尝试做的类比如下:
To clarify, the analogy in Python for what I'm trying to do would go as follows:
最简单:
n = 10
ls = [[0,0,0] for i in range(n)]
和也已经初始化,我可以访问元素(例如ls[0][0]
),甚至可以修改它们(ls[0][0]=2
),完美!
Already initialised as well and I can access elements (e.g. ls[0][0]
) and even modify them (ls[0][0]=2
), perfect!
或使用numpy
import numpy as np
n = 10 #number of elements
ls = np.empty((n,0)).tolist()
,然后将每个3个值附加到每个元素(这里是列表).
and then to each element (here a list), we'd append our 3 values.
现在我了解在C ++中,一个开始的区别是要专门定义内部列表应该包含的变量的类型.但是vector
不是c ++中的变量类型,对吗?就像这样:
Now I understand in C++, one starting difference would be to specifically define the type of variables the inner-lists are supposed to contain. But vector
is not a variable type in c++ right? As in something along the lines of:
int n = 4;
vector<vector> ls(4);
for(int i=0; i<n; i++) {
ls[i] = {0,0,0};
}
会错的.此外,如果我改用vector<int> ls;
,则无法为每个元素分配列表.
would be wrong. Moreover, if I try instead vector<int> ls;
then I cannot assign lists to each element.
问题:
- 有没有办法在C ++中使用
vector
使htis工作? - 或者,有没有更简单的方法可以做到这一点?
- Is there a way to make htis work using
vector
in C++? - Alternatively, are there simpler ways of going about this?
推荐答案
我能想到的最接近Python代码的是:
The closest to the Python code that I can think of is:
std::vector<std::vector<int>> ls(10, std::vector<int>(3));
如果在编译时知道大小,则也可以使用std::array
.
If the sizes are known at compile time, you may also use std::array
.
std::array<std::array<int, 3>, 10> ls;
这篇关于在C ++中创建列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!