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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:50:34  来源:igfitidea点击:

How to use vector::push_back()` with a struct?

c++vector

提问by XCS

How can I push_backa structinto a vector?

哪能push_backstruct成矢量?

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 pointa 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 ais a vector of points (not pointers to them), the push_back will create a copy of your point struct -- so pcan 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);