I'm trying to generate a quadratic grid with cells that have an ascending number.
#include <iostream>
#include <vector>
class Simple
{
public:
Simple(): id(genId()) {}
static int genId()
{
static int g_id = 0;
return ++g_id;
}
int id;
};
typedef std::vector< std::vector<Simple> > SimpleGrid;
void printSimpleGrid(SimpleGrid& grid)
{
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[i].size(); j++) {
std::cout << grid[i][j].id << " ";
}
std::cout << std::endl;
}
}
int main()
{
int dim = 3;
SimpleGrid test(dim);
for (int i=0; i<dim; i++) {
std::vector<Simple> row(dim);
test[i] = row;
}
printSimpleGrid(test);
return 0;
}
I get this output:
1 1 1
2 2 2
3 3 3
which differs from what I expected:
1 2 3
4 5 6
7 8 9
What am I doing wrong?
(I'm using Code::Blocks 12.11 rev 8629 with SDK version 1.13.14)
Elements can be inserted into a vector using the push_back() function of C++ STL. Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix.
Older/C++03 compilers will see this...
std::vector<Simple> row(dim);
...and match it to this overload of the constructor...
explicit vector( size_type count,
const T& value = T(),
const Allocator& alloc = Allocator());
...creating a prototypical Simple
object for the second constructor argument that is then copied to each of the dim
vector elements.
Newer/C++11 compilers will instead match this overload...
explicit vector( size_type count );
...then proceed to invoke the constructor dim
times to create the elements.
Details here
In addition to Tony D's great answer, here follows my happy end. In the IDE settings, I enabled C++11 compliance for the compiler. The Code::Blocks 12.11 package obviously supports not only one standard:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With