Preferred way to populate a vector of C ++ structures

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, definition of 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 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 directly to 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?

Edit: for the sake of this discussion, suppose assignments must be made one after another outside the constructor

+4
source share
4 answers

My option is to give the sticker a constructor that accepts parameters. then:

 board.push_back( Sticker( outline.x, foo.bar, etc. ) ); 

Edit: Code to illustrate constructor parameter names:

 #include <iostream> using namespace std; struct S { int a, b; S( int a, int b ) : a(a), b(b) { } }; int main() { S s( 1, 2); cout << sa << " " << sb << endl; } 
+16
source

board.resize (sticker_count);

Then iterate over the entire vector and set the parameters.

+2
source

Alternative 1. Why create a scope only for a variable? Usually there is a limited area nearby (at a minimum, you should keep your functions / procedures small in order to cover it).

Why? You can create a shorter variable name, for example. in this case. Since the appointment will be near, there should be no clarity. In fact, it will look easier and cleaner.

In addition, if a vector needs to be dereferenced / accessed from several other levels of indirection, it will also simplify the code.

0
source

How about winforms style:

 // Class members Sticker sticker1; Sticker sticker2; Board board; // Initialization void InitBoard() { sticker1.x = x + foreground.x; sticker1.y = foreground.y; sticker1.width = foreground.width; sticker1.height = foreground.height; sticker2.x = x + outline.x; sticker2.y = outline.y; sticker2.width = outline.width; sticker2.height = outline.height; // Add to board board.push_back(sticker1); board.push_back(sticker2); } 
0
source

Source: https://habr.com/ru/post/1305360/


All Articles