C++ 如何将 vector::push_back()` 与结构一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5289597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use vector::push_back()` with a struct?
提问by XCS
How can I push_back
a struct
into a vector?
哪能push_back
一struct
成矢量?
struct point {
int x;
int y;
};
std::vector<point> a;
a.push_back( ??? );
回答by Steve Jessop
point mypoint = {0, 1};
a.push_back(mypoint);
Or if you're allowed, give point
a constructor, so that you can use a temporary:
或者,如果允许,请提供point
一个构造函数,以便您可以使用临时:
a.push_back(point(0,1));
Some people will object if you put a constructor in a class declared with struct
, and it makes it non-POD, and maybe you aren't in control of the definition of point
. So this option might not be available to you. However, you can write a function which provides the same convenience:
如果您将构造函数放在用 声明的类中struct
,有些人会反对,这使它成为非 POD,而且您可能无法控制point
. 因此,您可能无法使用此选项。但是,您可以编写一个提供相同便利的函数:
point make_point(int x, int y) {
point mypoint = {x, y};
return mypoint;
}
a.push_back(make_point(0, 1));
回答by Wim
point p;
p.x = 1;
p.y = 2;
a.push_back(p);
Note that, since a
is a vector of points (not pointers to them), the push_back will create a copy of your point struct -- so p
can safely be destroyed once it goes out of scope.
请注意,由于a
是点向量(不是指向它们的指针),push_back 将创建点结构的副本——因此p
一旦超出范围就可以安全地销毁。
回答by Rewd0n
struct point {
int x;
int y;
};
vector <point> a;
a.push_back( {6,7} );
a.push_back( {5,8} );
Use the curly bracket.
使用大括号。
回答by The Communist Duck
point foo; //initialize with whatever
a.push_back(foo);