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

前端 未结 4 1350
遥遥无期
遥遥无期 2020-12-04 19:44

How can I push_back a struct into a vector?

struct point {
    int x;
    int y;
};

std::vector a;

a.push_back( ???          


        
4条回答
  •  北海茫月
    2020-12-04 20:04

    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.

提交回复
热议问题