Iām really new to c and c++
I tried to experiment with structs to create a list-like structure that can contain float and lists, basically.
This code compiles, but it behaves differently depending on the compiler:
with the latest version of visual studio community, it outputs
5
and then0
.with an online shell, I get
5
and then5
The one I would want to get is the second one when the vector gets passed through the function.
here is the code:
#include <iostream>
#include <vector>
using namespace std;
struct Box {
Box(char t) {
type = t;
}
union Value {
float number;
vector<Box>* elements;
};
Value value;
char type;
};
Box newBox() {
Box aBox('l');
vector<Box> newVec;
newVec.assign(5, Box('n'));
aBox.value.elements = &newVec;
cout << aBox.value.elements->size() << "\n";
return aBox;
}
int main()
{
Box test = newBox();
cout << test.value.elements->size(); // this is not always working nicely
}
Where does that come from?
Is there something wrong with my code?
And is there a better way to create this kind of structure?