Looking at your code:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
if (row == 0) {
grid[row].at(col) = col + 1;
}
else if (row == 1) {
int countByTwo = 2 * (col + 1);
grid[row].at(col) = countByTwo;
}
else if (row == 2) {
int countByThree = 3 * (col + 1);
grid[row].at(col) = countByThree;
}
|
You have a temporary variable in each branch (except the first) and it has different name each time.
While this does document the code, its added value is low. Lets be more systematic:
1 2 3 4 5 6 7 8 9 10 11 12
|
if (row == 0) {
int product = col + 1;
grid[row].at(col) = product;
}
else if (row == 1) {
int product = 2 * (col + 1);
grid[row].at(col) = product;
}
else if (row == 2) {
int product = 3 * (col + 1);
grid[row].at(col) = product;
}
|
The first case is still different from the rest. Lets be more explicit with it:
1 2 3 4
|
if (row == 0) {
int product = 1 * (col + 1);
grid[row].at(col) = product;
}
|
Now every case has a body similar to:
1 2
|
int product = N * (col + 1);
grid[row].at(col) = product;
|
Looking at all the cases, you should notice that in every case
row + 1 == N
This leads to the:
1 2 3 4 5 6
|
for (int row = 0; row < grid.size(); row++) {
for (int col = 0; col < grid[row].size(); col++) {
int product = (row + 1) * (col + 1);
grid[row].at(col) = product;
}
}
|
Vector has two member access methods: operator[] and function at(). The latter checks that index is valid and is thus usually slower, but safer.
You use a mixture.
If you want to play it safe, then use at() for both vectors:
grid.at(row).at(col) = product;
If you trust your indexing, then use [] for both:
grid[row][col] = product;
againtry wrote: |
---|
1 2
|
std::vector<std::vector<int>> table;
table.resize(13, std::vector<int>(13) );
|
|
Vector has
fill constructor (which stoneJax was already using). In your example:
std::vector<std::vector<int>> table(13, std::vector<int>(13) );