简体   繁体   中英

How to create multidimensional multitype c++ vector?

I'm looking for a way to create a C++ vector which will hold class object ( which is multi dimensional array - 3D coordinate system location mapper ) and int object which describes it in some way.

I have found many examples of multidimensional single type vectors like

vector <vector<int>> vec (4, vector<int>(4));

I need a dynamic structure which can grow/shrink in the heap as time progress with flexibility of the vector type.

// 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;

An alternative would be to define a Connection as an std::pair<Position, int> , but that wouldn't be very good because if you wanted to add more information to the Connection in the future, you'd have to change more code than you should.

If you want to resize the whole multidimensional array, you'll have to iterate over all the vectors one by one with a loop and call the resize method.

You can only get "type flexibility" out of a std::vector is to have it store a polymorphic type. Based on your example, it looks like you may want a std::vector of struct s:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM