开发者

Iterators and multi-dimensional vectors?

So, I am trying to build a two-dimensional vector that will hold indexes for selecting tiles from a tileset.

An iterator in one dimension is simple enough:

开发者_如何学Go
std::vector<int> vec;
std::vector<int>::iterator vec_it;

for(int i=5; i>0; --i){
  vec.push_back(i);   }

//prints "5 4 3 2 1 "
for(vec_it = vec.begin(); vec_it != vec.end(); ++vec_it){
  std::cout<<*vec_it<<' ';
}

However, I'm running into trouble when adding the second dimension. Here's the code that doesn't work:

std::vector<std::vector<int> > vec(5);
std::vector<std::vector<int> >::iterator vec_it;
std::vector<int>::iterator inner_it;

for(int i=0; i<5; ++i){
  vec[i].assign(5, 0);
}

for(vec_it = vec.begin(); vec_it != vec.end(); ++vec_it){
  for(inner_it = *vec_it->begin(); inner_it != *vec_it->end(); ++inner_it){
    std::cout<<*inner_it<<' ';
  }
  std::cout<<std::endl;
}

//should print:
//0 0 0 0 0
//0 0 0 0 0
//0 0 0 0 0
//0 0 0 0 0
//0 0 0 0 0

The compile fails with a nearly-incomprehensible error where I try to do inner_it = *vec_it->begin(), so I suppose my question is, how badly did I screw up?


vec_it->begin() dereferences vec_it, giving you a reference to the vector<int> and then returns the result of calling begin() on that. You shouldn't dereference the result of that using * (doing so dereferences the iterator, yielding the element pointed at by that iterator, which is an int in this case; you want the iterator itself).

Your inner for loop should look like:

for(inner_it = vec_it->begin(); inner_it != vec_it->end(); ++inner_it)


Remove the '*', you're simply assigning the iterator, so don't need to derefernce it.

for(inner_it = vec_it->begin(); inner_it != vec_it->end(); ++inner_it){
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜