0
vector<vector<int>> v(100, vector<int>(100)); // 101 vector<int> are created

I need to created a vector of vectors (or objects) like above. But then there will be 101 vector<int> created, which is one more I needed. If i understand it correctly, first a vector<int>(100) is created and then it's copied 100 times.

So I want to know if there's a way to avoid the reduncdant construction? Just create 100 elements.

  • 1
    The shown statement creates a 2D vector. That 2D vector has `100` elements each of which is a 1D vector with `100` elements. – Jason Mar 19 '22 at 17:21
  • 5
    Unless you really need the memory temporarily consumed by the extra vector, I wouldn't worry about it. The poor spatial locality of a vector of vectors will likely cost far more through extra cache misses. [Here is a simple alternative](https://stackoverflow.com/a/2076668/4581301) that will be exactly the right size and much quicker. – user4581301 Mar 19 '22 at 17:21
  • See [premature optimization](https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil) and save yourself the trouble of this level of micromanagement. The 100 `int`s worth of temporary storage saved by using Goswin's answer are vastly outweighed by how much more readable the original code snippet is than the proposed answer. – Silvio Mayolo Mar 19 '22 at 20:34
  • 1
    A vector of vectors is not the most efficient way to store a matrix anyhow, because of the double indirection. A single container with xy to linear mapping is more efficient. You might want to look at existing solutions like Eigen or Boost Ublas – JHBonarius Mar 19 '22 at 20:36
  • Thanks for your comment. I understand all your points. But `vector` can be replaced with any other type. I just want to know how to creat a vector of objects and initialize all the elements (not through default constructor). – Xiaofeng Zheng Mar 20 '22 at 18:20

1 Answers1

1

I guess the std::vector could handle this case with move semantics emplacing the first vector(100) at index 0 and doing 99 copies. But it doesn't.

But you can easily do that yourself:

vector<vector<int>> v;
v.reserve(100);
v.emplace_back(100);
for (int i = 1; i < 100; ++i) {
    v[i] = v[0];
}

You can do the same for the inner vector if you have a Matrix of complex objects where one extra copy is bad.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42