我正在尝试在我正在开发的游戏中打印出玩家的动作历史.在每轮结束时,每个玩家已经在正或负方向移动了一些数量,并在运动矢量中记录为int.最终我想要绘制每个玩家的方向移动到时间,但是我无法从2d向量中提取数据.
所以我尝试的第一件事是只是迭代和打印所有的元素,但是这不编译:
void output_movement(const std::vector< std::vector<int> > & movement){ std::vector< std::vector<int> >::iterator row; std::vector<int>::iterator col; for (row = movement.begin(); row != movement.end(); ++row) { for (col = row->begin(); col != row->end(); ++col) { std::cout << **col; } } }
编译器给出了我不太明白的错误信息:
hg_competition.cpp:45: error: no match for ‘operator=’ in ‘row = ((const std::vector<std::vector<int,std::allocator<int> >,std::allocator<std::vector<int,std::allocator<int> > > >*)money_movement)->std::vector<_Tp,_Alloc>::begin [with _Tp = std::vector<int,_Alloc = std::allocator<std::vector<int,std::allocator<int> > >]()’ /usr/include/c++/4.4/bits/stl_iterator.h:669: note: candidates are: __gnu_cxx::__normal_iterator<std::vector<int,std::allocator<int> >*,std::vector<std::vector<int,std::allocator<int> > > > >& __gnu_cxx::__normal_iterator<std::vector<int,std::allocator<int> > > > >::operator=(const __gnu_cxx::__normal_iterator<std::vector<int,std::allocator<int> > > > >&)
任何帮助是极大的赞赏!
解决方法
如果向量是const引用,则需要使用const_iterator.另外,要输出col,只需要取消引用它一次.
void output_movement(const std::vector< std::vector<int> > & movement){ std::vector< std::vector<int> >::const_iterator row; std::vector<int>::const_iterator col; for (row = movement.begin(); row != movement.end(); ++row) { for (col = row->begin(); col != row->end(); ++col) { std::cout << *col; } } }
编辑:使用typedef将使您的代码更易读
typedef std::vector<int> Vector; typedef std::vector<Vector> DoubleVector; void output_movement( const DoubleVector& movement ) { for (DoubleVector::const_iterator row = movement.begin(); row != movement.end(); ++row) { for (Vector::const_iterator col = row->begin(); col != row->end(); ++col) { std::cout << *col; } std::cout << std::endl; } }