[英]2D struct array member variable with varying sizes
So I've got a class that I'm generalizing into a base class. 所以我有一个要归纳为基类的类。 One of the member variables is a 2D array of a struct.
成员变量之一是结构的2D数组。
struct SomeType
{
...
}
and then in the class's header: 然后在类的标题中:
SomeType member_variable_ [SIZE_ONE][SIZE_TWO];
But, in my situation, SIZE_TWO
needs to be set when the class is initialized because it's going to be different depending on what's using this. 但是,在我的情况下,初始化类时需要设置
SIZE_TWO
,因为根据所使用的内容,它会有所不同。 What's the best way to have a 2D struct array with a size that's not yet set as a member variable? 拥有大小尚未设置为成员变量的2D结构数组的最佳方法是什么?
The simplest way to solve it is to not use C-style arrays at all, but to use std::vector
. 解决此问题的最简单方法是根本不使用C样式的数组,而要使用
std::vector
。 Or possibly an std::array
of vectors: 或者可能是向量的
std::array
:
std::array<std::vector<SomeType>, SIZE_ONE> member_variable_;
Now you can easily insert as many (or as few) SomeType
objects as needed, and still use the array-indexing syntax: 现在,您可以轻松地根据需要插入
SomeType
对象,并且仍然使用数组索引语法:
member_variable_[some_index][some_other_index]
To set a fixed size at runtime for the "second" Dimension, you can do something like this in the constructor: 要在运行时为“第二”维设置固定大小,可以在构造函数中执行以下操作:
for (auto& v : member_variable_)
v = std::vector<SomeType>(the_runtime_size);
You could use a template: 您可以使用模板:
template<unsigned SIZE_TWO>
class theClass
{
SomeType member_variable_ [SIZE_ONE][SIZE_TWO];
SIZE_TWO
will be set when you instantiate the class. 实例化类时将设置
SIZE_TWO
。
theClass<5> tc; //member_variable_ [SIZE_ONE][5];
You could also use containers like std::vector
or std::array
. 您也可以使用
std::vector
或std::array
类的容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.