Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple value in vector in C++?

Tags:

c++

I want to know that is there any way that we can insert a multiple values in a vector as a single value without using a temp variable?

I mean for example:

struct Something{
    int x;
    int y;
};
int main()
{  
    vector <Something> v;
    int x, y;
    cin >> x >> y;
    v.push_back(x, y);
}

Is there any way that we avoid doing this(defining another variable, then inserting that, instead of insert x, y directly):

Something temp;
temp.x = x;
temp.y = y;
v.push_back(temp);
like image 939
Milad R Avatar asked Nov 27 '22 11:11

Milad R


1 Answers

Give your class a constructor, like this:

Something(int x_, int y_) :x(x_), y(y_) {}

Then you can just do this:

v.push_back(Something(x,y));

In C++11, you can do this, without the constructor:

v.push_back({x,y});
like image 175
Benjamin Lindley Avatar answered Dec 18 '22 08:12

Benjamin Lindley