Reputation: 29
Can anyone help me with why this code give me a segmentation fault on the inner loop?
I am trying to iterate on a list of vectors of some class block.
class chain
{
list<vector<Block*>* >* _blockChain;
}
Chain* someChain = new Chain();
for(list<vector<Block*>*>::iterator listIter = someChain->getChain()->end() ;
listIter != someChain->getChain()->begin(); listIter--)
{
for(vector<Block*>::iterator it = (*listIter)->begin();
it != (*listIter)->end() ; it++)
{
//do something
}
}
Upvotes: 0
Views: 69
Reputation: 490048
If you want to iterate through the list in reverse, use a reverse_iterator:
for(list<vector<Block*>*>::reverse_iterator listIter = someChain->getChain()->rbegin();
listIter != someChain->getChain()->rend(); ++listIter)
With a recent compiler you can condense that down a bit:
for (auto listIter = someChain->getChain()->rbegin();
listIter != someChain->getChain()->rend(); ++listIter)
That said, I agree with @Mike Seymour: you are using way too many pointers. For one really obvious example, there's almost never a reason to use a pointer to a vector (because a vector is itself little more than a wrapper around a pointer to data, with a little extra data for book-keeping about how much data is in the vector).
Upvotes: 1
Reputation: 3737
I think you face a crash in List::end()
and List::begin()
. It's because you has not initialized your List
anywhere in your code (at least I don't see in your given code). you need:
class Chain{
Chain()
{
_blockChain = new list<vector<int*>* >;
// initializing Vector and so on
}
};
Although this is not all of your problems.
Upvotes: 0
Reputation: 180415
The first time you try to access listIter
it is pointing to end()
which is not to be dereferenced. In the inner loop you dereference listIter
and try to use it.
From http://en.cppreference.com/w/cpp/container/vector/end
This element acts as a placeholder; attempting to access it results in undefined behavior.
Upvotes: 1