Reputation: 71
I try to initialize structures of vectors that contains vector:
struct productionCanvas
{
int canvasID;
int indexXmlJob;
};
struct productionArea
{
int areaID;
std::vector<productionCanvas> canvasList;
};
The first level is correctly initialized but not the second one:
int areaIncr=0;
int canvasIncr=0;
std::vector<productionArea> production;
int addArea()
{
productionArea area{};
areaIncr++;
area.areaID = areaIncr;
area.canvasList = {};
production.push_back(area);
return areaIncr;
}
int addCanvas(int job)
{
productionCanvas canvas{};
canvasIncr++;
canvas.canvasID = canvasIncr;
canvas.indexXmlJob = job;
for (productionArea area : production)
{
if (area.areaID == areaIncr)
{
area.canvasList.push_back(canvas); // this line is triggered
break;
}
}
// Check if correctly push_back
for (productionArea area : production)
{
for (productionCanvas canvas : area.canvasList)
{
// This line is never triggered, why ?
}
}
return canvasIncr;
}
addArea(); // area correctly inserted
addCanvas(1); // canvas not inserted inside area
.
There is no return value of the push_back function, so I cannot know why it's not pushed back! It seemed that it does not work like Qt-QVector.
How to initialize these struct?
Upvotes: 0
Views: 163
Reputation: 19113
You can zero-initialize any POD struct or array by simply adding {}
:
productionArea area{};
// Or
productionArea area = {};
// Or
auto area = productionArea{};
Unless you are working in C/C++ environment, there is no need for typedef struct
in C++. The symbol namespaces are not separate. This is equal to your current code:
struct productionCanvas_def
{
int canvasID;
int indexXmlJob;
} productionCanvas;
You can even initialize each member:
struct foo{
int a{2};
int a{4};
};
But then it is no longer POD.
The problem is here:
for (productionArea area : production) // <-- The `area` is a copy of
// the one in the container.
{
if (area.areaID == areaIncr)
{
area.canvasList.push_back(canvas); // this line is triggered
break;
}
}
To modify elements in place, you have to use references for(productionArea &area : production)
Upvotes: 1
Reputation: 610
it doesn't look like c++ , but the below code wiil not run as your canvasList with empty in addArea
area.canvasList = {};
Upvotes: 0