如何创建多维多类型c++向量
How to create multidimensional multitype c++ vector?
我正在寻找一种方法来创建一个C++向量,它将包含类对象(它是多维数组-三维坐标系位置映射器)和以某种方式描述它的int对象。
我发现了许多像这样的多维单一类型向量的例子
vector <vector<int>> vec (4, vector<int>(4));
我需要一个动态结构,它可以随着时间的推移在堆中增长/收缩,并具有向量类型的灵活性。
// Your position object, whatever the declaration may be
struct Position { int x, y, z; };
struct Connection {
Position position;
int strength;
};
// This is what you want your node class to be
// based on the comment you gave.
struct Node {
Position position;
std::vector<Connection> connections;
};
// A vector is dynamic and resizable.
// Use std::vector::push_back and std::vector::emplace_back methods
// insert elements at the end, and use the resize method to modify
// the current size and capacity of the vector.
std::vector<std::vector<std::vector<Node>>> matrix;
另一种选择是将Connection
定义为std::pair<Position, int>
,但这不是很好,因为如果您想在未来向Connection添加更多信息,则必须更改超出应有数量的代码。
如果要调整整个多维数组的大小,则必须使用循环逐个迭代所有向量,并调用resize
方法。
您只能从std::vector
中获得"类型灵活性",即让它存储多态类型。根据您的示例,您可能想要struct
的std::vector
:
struct s
{
int i;
double d;
char c;
bool b;
};
std::vector<s> vec;
// elements can be accessed as such:
auto i = vec[0].i;
auto d = vec[0].d;
auto c = vec[0].c;
auto b = vec[0].b;
相关文章:
- 实现多类型算术运算符时如何解决"template argument deduction/substitution failure"
- 如何使用模板处理多类型变量?
- 如何获取多类型向量中的值(不添加 <type>)?
- C++:是否可以制作多类型函数参数?
- 在模板专业化中添加更多类型
- 多类型标准映射
- 多类型数据类 c++
- C3857不允许使用多类型参数列表编译器错误
- 有没有一种更干净的方法可以在c++(11)中复制具有多类型值的无序映射
- C++中的多类型容器
- C++多类型数组
- 多类型容器(数组/向量/列表)传统上是如何在C++实现的?(当然没有元组)
- C++ 多类型对象的想法
- 如何创建多维多类型c++向量
- 将多类型数据存储在非类型化存储器空间中
- 在单个结构下管理多类型对象
- c++多类型模板使用指南
- 多类型的c++映射
- 多态性中的多类型输出
- 如何使用模板编程创建多类型数组