将一个结构push_back()一个向量 [英] push_back() a struct into a vector
本文介绍了将一个结构push_back()一个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将一个结构push_back到一个向量?
How can I push_back a struct into a vector?
struct point {
int x;
int y;
};
vector <point> a;
a.push_back( ??? );
推荐答案
point mypoint = {0, 1};
a.push_back(mypoint);
或者如果允许,请给予点
一个构造函数,所以你可以使用一个临时的:
Or if you're allowed, give point
a constructor, so that you can use a temporary:
a.push_back(point(0,1));
有些人会对象,如果你把一个构造函数声明为 struct
,它使它非POD,也许你不能控制 point
的定义。因此,此选项可能不适用于您。但是,你可以编写一个方便的函数:
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:
point make_point(int x, int y) {
point mypoint = {x, y};
return mypoint;
}
a.push_back(make_point(0, 1));
这篇关于将一个结构push_back()一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文