简体   繁体   中英

C++: Can I change a vector type?

Let's assume I have the following code:

typedef struct foo{
    int x;
}foo;

typedef struct bar{
    int y
}bar;

struct foobar{
    std::vector<foo> foo1;
    std::vector<bar> bar1;
};

Is there any way to change std::vector<bar> bar1; into std::vector<foo> bar1; and erase any data inside?

And if so, could this be done in a function? Something like this?

replaceBar(&myOwnStruct);

I am not too great with vectors, so an explanaitaion to why this is/isn't possible would be nice. Thanks!

The way to "change" a variable's type (which is not really possible in C++) from one type to another is to use std::variant to indicate the possible types it is allowed to hold (or, use std::any to hold all types), eg:

std::variant<std::vector<bar>, std::vector<foo>> bar1;

You could then have bar1 hold a std::vector<bar> initially, and then at a later time reassign it to hold a std::vector<foo> instead.

struct foo{
    int x;
};

struct bar{
    int y;
};

struct foobar{
    std::vector<foo> foo1;
    std::variant<std::vector<bar>, std::vector<foo>> bar1;
};

void replaceBar(foobar *fb) {
    fb->bar1 = std::vector<foo>{};
}

foobar myOwnStruct;
foobar.bar1 = std::vector<bar>{};
replaceBar(&myOwnStruct);

Possibility 1: If foo and bar can have a common base class. You could then have the vector be of pointers to the base class. You can then re-point the pointer to a different object. But it will reallocate memory. Not exactly what you wanted.
Possibility 2: You could declare a union. But note that the vector's memory is on heap so it doesnt really achieve your objective and you'll have to be careful about destructors. If it were plain object arrays with fixed sizes, you could do it.
Possiblity 3: This may work for you in games. Instead of storing a vector directly, store a flatbuffers serialized block of bytes. You can rewrite a different thing into those bytes. You'll need another variable in the struct to say what's in those bytes. Maybe this option is too far out there for you !

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