How to insert multiple values ​​into a vector in C ++?

I want to know that there is some way that we can insert multiple values ​​into a vector as one value without using a temporary 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 a way to avoid this (defining another variable and then pasting this instead of directly pasting x, y ):

 Something temp; temp.x = x; temp.y = y; v.push_back(temp); 
+4
source share
4 answers

Give your class a constructor, for example:

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

Then you can simply do this:

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

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

 v.push_back({x,y}); 
+13
source

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

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

This assumes your Something class has a constructor (int, int) . Otherwise, you can use push_back with a parenthesis initializer, as in Benjamin's answer. (Both versions will likely generate identical code when working with the smart compiler, and you may like to save your class as a collection.)

+8
source

In C ++ 11, you can do this:

 v.push_back({1,2}); 

You do not need to write a constructor as suggested by another answer.

+7
source

This does not work in C ++ 11 Visual Studio 2012 unless you have downloaded and updated the beta version manually. It is currently not in the final version, but in a few months it will probably work with automatic updates.

+1
source

Source: https://habr.com/ru/post/1401861/


All Articles