[英]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) (我正在使用Code :: Blocks 12.11 rev 8629和SDK版本1.13.14)
Older/C++03 compilers will see this... 旧版/ C ++ 03编译器会看到这个......
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. ...为第二个构造函数参数创建一个原型
Simple
对象,然后将其复制到每个dim
向量元素中。
Newer/C++11 compilers will instead match this overload... 较新的/ C ++ 11编译器将匹配此重载...
explicit vector( size_type count );
...then proceed to invoke the constructor dim
times to create the elements. ...然后继续调用构造函数
dim
时间来创建元素。
In addition to Tony D's great answer , here follows my happy end . 除了Tony D的好回答之外 ,这里也是我快乐的结局 。 In the IDE settings, I enabled C++11 compliance for the compiler.
在IDE设置中,我为编译器启用了C ++ 11合规性。 The Code::Blocks 12.11 package obviously supports not only one standard:
Code :: Blocks 12.11包显然不仅支持一个标准:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.