I have some trouble understanding the output from the following code:
int main(void)
{
vector<TreeNode> tree;
for(int i = 0; i < 50; i++)
{
TreeNode node;
tree.push_back(node);
}
for(int i = 0; i < 50; i++)
{
Image image;
image.Path = "TestPath";
image.Votes = 0;
TreeNode node = tree.at(i);
node.images.push_back(image);
node.images.push_back(image);
}
TreeNode node = tree.at(0);
cout << "TEST" << endl;
cout << node.images.size() << endl;
}
Output:
TEST
0
Why is the output 0 and what should I do to fix it? I would expect the size to be 2 and not 0.
It has probably something to do with how structs work. My two defined structs is as follow:
typedef struct
{
string Path;
int Votes;
} Image;
typedef struct
{
int treeIndex;
float centroid;
vector<float*> features;
vector<Image> images;
} TreeNode;
Note that it is not an option for me to use classes instead of structs.
vector::at returns a reference to an object.
Your line
is creating a copy of the TreeNode in node, so when you add images to it, it’s adding them to a new object that’s not in your vector.
If you instead use
It will add the images correctly.