Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems initializing a vector of vectors of an auto-inc type

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)

like image 538
Wolf Avatar asked Jun 16 '14 12:06

Wolf


People also ask

How do you add elements to a 2D vector?

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.


2 Answers

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

like image 120
Tony Delroy Avatar answered Nov 14 '22 22:11

Tony Delroy


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:

enter image description here

like image 30
Wolf Avatar answered Nov 14 '22 23:11

Wolf