如何在C ++中向量中插入多个值? [英] How to insert multiple value in vector in C++?
本文介绍了如何在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?
我的意思是示例:
struct Something{
int x;
int y;
};
int main()
{
vector <Something> v;
int x, y;
cin >> x >> y;
v.push_back(x, y);
}
有没有办法避免这样做(定义另一个变量, ,而不是直接插入 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);
推荐答案
给你的类一个构造函数, p>
Give your class a constructor, like this:
Something(int x_, int y_) :x(x_), y(y_) {}
然后你可以这样做:
v.push_back(Something(x,y));
在C ++ 11中,您可以执行此操作,而不使用构造函数:
In C++11, you can do this, without the constructor:
v.push_back({x,y});
这篇关于如何在C ++中向量中插入多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文