简体   繁体   中英

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

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:

v.push_back({x,y});

In C++11, you can use emplacement functions:

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

This assumes that your Something class has an (int, int) constructor. Otherwise you can use push_back with a brace initializer, as in Benjamin's answer. (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:

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. Currently it is not in it's final release, but a few months from now it will probably be working with an auto update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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