填充结构的C ++向量的首选方法

时间:2010-03-28 15:29:11

标签: c++ vector

备选方案1,重用临时变量:

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);

备选方案2,确定临时变量的范围:

{
 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);
}

备选方案3,直接写入矢量存储器:

{
 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;
}

您更喜欢哪种方式?

编辑:为了便于讨论,假设必须在构造函数之外逐个进行赋值

4 个答案:

答案 0 :(得分:16)

我的选项 - 为Sticker提供一个获取参数的构造函数。然后:

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

编辑:用于说明构造函数参数名称的代码:

#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;
}

答案 1 :(得分:2)

board.resize(sticker_count);

然后遍历所有向量并设置参数。

答案 2 :(得分:0)

备选方案1.为什么仅为变量创建范围?附近通常有一个封闭的范围(至少,您应该保持您的功能/程序较小,以便将其范围扩大)。

为什么呢?您可以创建一个较短的变量名,例如在这种情况下。由于任务将在附近,因此不应有明显的损失。实际上它看起来更简单,更清洁。

此外,如果需要从其他几个间接级别取消引用/访问向量,那么它也将简化代码。

答案 3 :(得分:0)

winforms风格怎么样:

// 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);
}