Preferred way of filling up a C++ vector of structs
- by henle
Alternative 1, reusing a temporary variable:
Sticker sticker;
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
board.push_back(sticker);
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
board.push_back(sticker);
Alternative 2, scoping the temporary variable:
{
Sticker sticker;
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
board.push_back(sticker);
}
{
Sticker sticker;
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
board.push_back(sticker);
}
Alternative 3, writing straight to the vector memory:
{
board.push_back(Sticker());
Sticker &sticker = board.back();
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
}
{
board.push_back(Sticker());
Sticker &sticker = board.back();
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
}
Which approach do you prefer?