C++ vector > reserve size at beginning

2020-04-21 08:28发布

问题:

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!

回答1:

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.



回答2:

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

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



回答3:

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));


回答4:

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;
}