Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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

How can I push_back a struct into a vector?

struct point {
    int x;
    int y;
};

std::vector<point> a;

a.push_back( ??? );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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));

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...