c++ - Foreach 通过包含 C++ 中的指针的 vector

标签 c++ for-loop dictionary vector iterator

我制作了一个充满 vector 的 map ,看起来像这样:

std::map<int, std::vector<CClass*>> pointers = getMap();

现在我想遍历 map 的每个槽位以及存储在 map 中的 vector 的每个槽位。

这是它通过 map 的方式:

for (std::map<int, std::vector<CClass*>>::iterator it = pointers.begin(); it != pointers.end(); it++) 

这很好用,它会像我希望的那样遍历每个对象。

但现在我想遍历 vector 中的每个槽,我这样试过:

for (std::vector<CClass*>::iterator playerIt = it->second.begin(); playerIt != it->second.end(); playerIt++) 

如果我想访问存储在其中的值,编译器会给我这个错误:

file.cpp(552) : error C2839: Ungültiger Rückgabetyp 'CClass **' für überladenen Operator '->'

这意味着“超重运算符'->'的无效返回类型'CClass **'

问候

最佳答案

您可以在 C++11 中使用基于范围的 for 循环来更易读地处理此问题

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
    }
}

关于c++ - Foreach 通过包含 C++ 中的指针的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28611600/

相关文章:

python - 在迭代中将 "if condition"存储为变量是否合适

python - 从数据框中列表内的字典中提取元素

python - 在字典中覆盖 Python 的哈希函数

python 二维数组来听写

c++ - 将 JSON 插入 Mongocxx

c++ - 在 Linux 中获取有关进程的信息

c++ - 使用Windows API创建快捷方式.lnk

javascript - Array.map() 与 for 循环对字符串进行标题封装

c++ - 当将新对象分配给其地址时,是否必须销毁该对象?

c - 在c代码的for循环中重置变量