1

in c++ I have

vector<vector<int> > table;

How can I resize vector so that it has 3 rows and 4 columns, all zeros?

Something like that:

0000 0000 0000

So that I could later change for example

table[1][2] = 50;

I know i can do this with for loop, but is there other way?

In 1 dimensional vector I could have:

vector<int> myvector(5);

And i could then type for example:

myvector[3]=50;

So, my question is how to do it with 2 dimensional, or even multidimensional vector?

Thanks!

Dominik
  • 17
  • 9
  • I've tried to answer this (and obviously others have too) but it's really unclear. Reserve or resize? "how to do it" do _what_? _I_ can see that you're asking how to pass initial size at construction for nested vectors, but in order for this to remain a good part of the SO Q&A repository it ought to be tidied up. – Lightness Races in Orbit Jan 22 '15 at 11:29

4 Answers4

3
vector<vector<int> > table(3, vector<int>(4,0));

This creates a vector with 3 rows and 4 columns all initialized to 0

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
2

You can use resize() from std::vector :

 table.resize(4);                           // resize the columns
 for (auto &row : table) { row.resize(3); } // resize the rows

Or you can directly initialize it as :

std::vector<std::vector<int>> table(4,std::vector<int>(3));
coincoin
  • 4,595
  • 3
  • 23
  • 47
2

You can pass an explicit default value to the constructor:

vector<string> example(100, "example");  
vector<vector<int>> table (3, vector<int>(4));
vector<vector<vector<int>>> notveryreadable (3, vector<vector<int>>(4, vector<int> (5, 999)));

The last one is more readable if it's built "piecewise":

vector<int> dimension1(5, 999);
vector<vector<int>> dimension2(4, dimension1);
vector<vector<vector<int>>> dimension3(3, dimension2);

particularly if you use explicit std:: - code that looks like

std::vector<std::vector<std::vector<std::string>>> lol(3, std::vector<std::vector<std::string>>(4, std::vector<std::string> (5, "lol")));

should be reserved for bad jokes.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

Don't! You'll have complex code and rubbish memory locality.

Instead have a vector of twelve integers, wrapped by a class that converts 2D indices into 1D indices.

template<typename T>
struct matrix
{
   matrix(unsigned m, unsigned n)
     : m(m)
     , n(n)
     , vs(m*n)
   {}

   T& operator()(unsigned i, unsigned j)
   {
      return vs[i + m * j];
   }

private:
   unsigned m;
   unsigned n;
   std::vector<T> vs;
};

int main()
{
   matrix<int> m(3, 4);   // <-- there's your initialisation
   m(1, 1) = 3;
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055