矢量控股只读矩阵?

时间:2010-06-17 13:58:33

标签: c++ vector matrix const

我想使用向量来保存大小为5x5的只读整数矩阵

vector<const int[5][5]> startingPieces;

但是这个宣言引起了一系列我以前从未见过的奇怪错误。

error C2535: 'const int (*std::allocator<_Ty>::address(const int (&)[5][5]) const)[5][5]' : member function already defined or declared
1>        with
1>        [
1>            _Ty=const int [5][5]
1>        ]
1>        c:\program files\microsoft visual studio 9.0\vc\include\xmemory(109) : see declaration of 'std::allocator<_Ty>::address'
1>        with
1>        [
1>            _Ty=const int [5][5]
1>        ]
1>        c:\program files\microsoft visual studio 9.0\vc\include\vector(429) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=const int [5][5]
1>        ]
1>        c:\program files\microsoft visual studio 9.0\vc\include\vector(439) : see reference to class template instantiation 'std::_Vector_val<_Ty,_Alloc>' being compiled
1>        with
1>        [
1>            _Ty=const int [5][5],
1>            _Alloc=std::allocator<const int [5][5]>
1>        ]
1>        c:\users\eric\documents\visual studio 2008\projects\testing grounds\testing grounds\main.cpp(14) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=const int [5][5]
1>        ]

那么,这个宣言有什么问题?

3 个答案:

答案 0 :(得分:7)

两件事 - 首先矢量不能容纳const对象 - 有关此问题的讨论,请参阅Can I use const in vectors to allow adding elements, but not modifications to the already added?。其次,他们不能保存数组,因为他们持有的东西必须是可复制和可分配的,而数组也不是。

答案 1 :(得分:2)

你应该在这里做的是创建你自己的矩阵类,它存储5x5数据数组,然后用它创建你的矢量。

答案 2 :(得分:1)

一种方法是使用the array class(您的实施可能支持std::arraystd::tr1::array;如果没有,您可以使用Boost库中的boost::array

std::vector<std::array<std::array<int, 5> > >

存储在容器中的元素仍然不能是const;如果适用于您的用例,您可以创建整个向量const。