Reputation: 25
I'm sitting in front of a problem where I don't know the solution. In the end im always getting an segmentation fault.
I've created a "Map"-class where I store the following informations and this Map is stored as a Vector inside the Gameclass
class Map
{
private:
unsigned int map_id_;
unsigned int map_width_;
unsigned int map_height_;
std::vector< std::vector< int > > fields_;
Game *game_;
class Game
{
private:
...
std::vector< Map* > *v_map_;
...
std::vector< Map* > Game::getMapVector()
{
return *v_map_;
}
Inside the Game-Class I fill up the informations, including the fields vector.
for(int i = 0; i < height; i++)
{
std::vector< int > row;
for (int j = 0; j < width; j++)
{
is.read(reinterpret_cast<char*>(&fields), 1);
counter = counter - 1;
row.push_back(int(fields));
}
fields_vector.push_back(row);
}
If i try to output my map direct in the readin-process everything works perfect.
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
std::cout << fields_vector[i][j];
}
std::cout << std::endl;
}
Until now everything is ok. But now I'm getting the segmentationfault if I call it with an for-loop inside the auto iterator.
If I try it to output only one element with std::cout << (*it)->getMapFields()[1][1]
inside the first for-loop i get the correct output on this position.
for(auto it = std::begin(game.getMapVector()); it != std::end(game.getMapVector()); it++)
{
std::cout << "ID: " << (*it)->getMapId()
<< ", width: " << (*it)->getMapWidth()
<< ", height: " << (*it)->getMapHeight() << std::endl;
for (int i = 0; i < (*it)->getMapHeight(); i++)
{
for (int j = 0; j < (*it)->getMapWidth(); j++)
{
std::cout << (*it)->getMapFields()[i][j];
}
std::cout << std::endl;
}
}
Is there something i didn't see? Maybe an for-loop inside an auto iterator isn't possible?
Thanks in advance for helping, Philipp
Upvotes: 0
Views: 194
Reputation: 122001
One mistake is:
std::vector< Map* > Game::getMapVector()
returns a new std::vector<Map*>
instance. This means that the begin
and end
iterators used in the following for
loop refer to different std::vector
instances:
for(auto it = std::begin(game.getMapVector());
it != std::end(game.getMapVector());
it++)
Possible solutions:
getMapVector()
to a local variable and use it for iterationgetMapVector()
to return a (const
) reference to the std::vector<Map*>
Upvotes: 5