开发者

Preferred way of filling up a C++ vector of structs

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?

Edit: For the sake of this discussion, assume that the assignments have to be made one by one outside of a constr开发者_开发问答uctor


My option - give Sticker a constructor that takes the 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 << s.a << " " << s.b << endl;
}


board.resize(sticker_count);

Then iterate through all the vector and set parameters.


Alternative 1. Why create a scope just for a variable? There is usually an enclosing scope nearby (at the minimum, you should keep your functions/procedures small so that will scope it).

Why? You can create a shorter variable name e.g. st in this case. Since the assignment will be nearby there should be no loss in clarity. Actually it will look simpler and cleaner.

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜