简体   繁体   English

如何在C ++中向量中插入多个值?

[英]How to insert multiple value in vector in 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): 有没有办法我们避免这样做(定义另一个变量,然后插入,而不是直接插入x, y ):

Something temp;
temp.x = x;
temp.y = y;
v.push_back(temp);

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: 在C ++ 11中,您可以在没有构造函数的情况下执行此操作:

v.push_back({x,y});

In C++11, you can use emplacement functions: 在C ++ 11中,您可以使用安置功能:

if (std::cin >> x >> y)
{
    v.emplace_back(x, y);
}
else { /* error */ }

This assumes that your Something class has an (int, int) constructor. 这假设你的Something类有一个(int, int)构造函数。 Otherwise you can use push_back with a brace initializer, as in Benjamin's answer. 否则你可以使用带有大括号初始化程序的push_back ,就像Benjamin的回答一样。 (Both versions are probably going to produce identical code when run through a clever compiler, and you may like to keep your class as an aggregate.) (两个版本在运行聪明的编译器时可能会生成相同的代码,您可能希望将类保留为聚合。)

In C++11, you can do this: 在C ++ 11中,您可以这样做:

v.push_back({1,2});

You don't need to write a constructor as suggested by other answer. 您不需要像其他答案所建议的那样编写构造函数。

This doesn't work in C++11 Visual Studio 2012 unless you have manually downloaded and updated to the Beta version. 除非您已手动下载并更新到Beta版本,否则这在C ++ 11 Visual Studio 2012中不起作用。 Currently it is not in it's final release, but a few months from now it will probably be working with an auto update. 目前它不是最终版本,但从现在开始几个月它可能会使用自动更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM