如何创建多维多类型c++向量

How to create multidimensional multitype c++ vector?

本文关键字:多类型 c++ 向量 何创建 创建      更新时间:2023-10-16

我正在寻找一种方法来创建一个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中获得"类型灵活性",即让它存储多态类型。根据您的示例,您可能想要structstd::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;