in c++ I have
vector > table;
How can I resize vector so that it has 3 rows and 4 columns, all zeros?
Someth
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.
vector<vector<int> > table(3, vector<int>(4,0));
This creates a vector with 3 rows and 4 columns all initialized to 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;
}
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));