Question

It may seems obvious for some of you, but I am trying to add an element to a multi-dimensional vector (better to say vector of vectors) in a single line. The usual way could be:

std::vector<int> vec1;
std::vector< std::vector<int> > vec_vec;
int a = 5; 
vec1.push_back(a);
vec_vec.push_back(vec1);

What I tried to do is to compress the last three lines into one line. I am wondering if it is possible to do that.
Please note that I am not aware of the the size of the vec_vec. The only thing I know is the location where I would insert my element.

NOTE: I am working with C++98.

Was it helpful?

Solution

How about

using V = std::vector<int>;
std::vector<V> vec_vec;
vec_vec.push_back(V(1, 5));

or just (thanks melak47)

std::vector< std::vector<int> > vec_vec;
vec_vec.push_back({5});

or

std::vector< std::vector<int> > vec_vec;
vec_vec.emplace_back(1, 5);

The second version is shorter, the third is maybe more efficient, but this depends on optimization.

OTHER TIPS

Since original requirement was to be able to insert at any position without knowing any sizes beforehand in one line of code, I think most general solution would be:

std::vector< std::vector<int> > vec_vec;

//assuming we want insert 5 at position [i][j] 
int i=3,j=4;

vec_vec.size() <= i ? (vec_vec.resize(i+1,std::vector<int>(j+1,0)), vec_vec[i][j]=5) : (vec_vec[i].size() <= j  ? (vec_vec[i].resize(j+1,0), vec_vec[i][j] = 5) : vec_vec[i][j] = 5);

It inserts 5 at position [3][4] examining all sizes and re-sizing components if necessary all in one line (all newly added elements are default initialized to 0, all elements already present are kept unchanged, result is guaranteed to be at least (i+1)x(j+1) in size after insertion).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top