I made a map filled with vectors which looks like this:
std::map<int, std::vector<CClass*>> pointers = getMap();
And now I want to go through every slot of the map and also through every slot of the vector stored in the map.
This is how it goes through the map:
for (std::map<int, std::vector<CClass*>>::iterator it = pointers.begin(); it != pointers.end(); it++)
This works fine and it goes through every object just like I want it to.
But now I want to go through every slot in the vector and I tried it like this:
for (std::vector<CClass*>::iterator playerIt = it->second.begin(); playerIt != it->second.end(); playerIt++)
If I want to access the value stored in it the compiler gives me this error:
file.cpp(552) : error C2839: Ungültiger Rückgabetyp 'CClass **' für überladenen Operator '->'
Which means "invalid return-type 'CClass **' for overweight operator '->'
regards
You can use range-based for loops in C++11 to handle this more readably
for (auto& element : pointers)
{
for (auto& player : element.second)
{
// player will be a CClass* that you can use
std::string name = player->GetName(); // For example
}
}
playerIt
is an iterator, not a pointer to a CClass
. You need to dereference the iterator to get a pointer to CClass
:
CClass * player = (*playerIt);
player->ClassMethod(...); // or whatever
playerIt
is an iterator that returns a CClass*
, but you dereference the iterator via operator->, so you need to dereference the pointer that is returned by the iterator.
So you are possibly saying playerIt->cclass_method()
when you should be saying (*playerIt)->cclass_method();
Of course, storing shared_ptr<>, or unique_ptr objects in your vector might be better and easier to understand, along with using typedef to alias the vector<> part of the map.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.