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 ?
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 int
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With