gpt4 book ai didi

c++ - 填充 C++ 结构 vector 的首选方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:48 26 4
gpt4 key购买 nike

备选方案 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);
}

方案三,直接写入 vector 内存:

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

您更喜欢哪种方法?

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

最佳答案

我的选择 - 为 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;
}

关于c++ - 填充 C++ 结构 vector 的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2533411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com