Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to immediately insert a vector inside a vector?

Tags:

c++

stl

vector

I have a vector which elements are of type vector<int>, I want to quickly insert elements like this :

triangles.push_back(vector<int>(som1, som2, som3))

However it doesn't work, no constructor of vector<int> matches the argument list.

Is there a quick way to do it, or do I have to create a temporary vector<int> variable, push back som1 som 2 and som3, and finally push back the temporary variable in triangles ?

like image 672
user3723620 Avatar asked Nov 10 '22 06:11

user3723620


1 Answers

If you can't use C++11 initializer lists, all is not lost. Given that your vector is named triangles, I'm going to assume each sub-vector will always contain exactly three ints. If that's the case, you can use a helper function:

std::vector<int> MakeTriangle(int a, int b, int c)
{
   std::vector<int> triangle(3);
   triangle[0] = a;
   triangle[1] = b;
   triangle[2] = c;
   return triangle;
}

void f()
{
   std::vector<std::vector<int>> triangles;
   triangles.push_back(MakeTriangle(1, 2, 3));
}

For the more general problem, you could write a set of MakeVector() function templates taking various numbers of arguments, up to some reasonable limit (again, if you don't have C++11).

If you have boost in your project, you could also make use of boost::assign. But I wouldn't drag the entire boost library in just to solve this problem.

like image 55
dlf Avatar answered Nov 15 '22 07:11

dlf