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:
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()dereferencesvec_it, giving you a reference to thevector<int>and then returns the result of callingbegin()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 anintin this case; you want the iterator itself).Your inner for loop should look like: