c++ - 指针不可从列表中取消引用

标签 c++ list pointers

我有两个类 Player 和 Team,其中每个 player 类都有一个指向团队的指针

class Player{
private: Team* team;}

并且每个团队都有一个指向球员的指针列表

class Team{
private: list<Player*> playerlist;}

现在我想通过在列表中称呼某个球员来了解他在哪个球队踢球。之后,我希望能够向团队提出诸如 team.getid() 之类的内容

我为一个函数尝试了以下解决方案:

std::list<Team>::iterator* teamsearch(std::list<Team> a, int b)
{
    int i = 0;
    std::list<Team>::iterator Listitem;
    std::list<Team>::iterator* Listitemtest = &Listitem;
    while (i == 0){
        for (Listitem = a.begin(); Listitem != a.end(); ++Listitem)
        {
            if (Listitem->getteamID_() == b)
                i++;
            Listitemtest = &Listitem;
        }

    };
    std::cout << "TeamID: " << (*Listitemtest)->getteamID_() << std::endl;
    return Listitemtest;
}

这个想法是它返回一个指向玩家团队地址的迭代器。这是正确的吗?

然后我尝试通过这种方式再次取消引用迭代器来解决团队问题:

Team team;
team.setteamID_(0);
team.setteamname_("team1");
Teamvector.push_back(team);
std::list<Team>::iterator Listitem;
Listitem = *teamsearch(Teamvector, 0);

这让我在 MSVC120.dll 中出现运行时错误 ...include\list: list iterator not derefencable

迭代器似乎指向团队列表的末尾?

最佳答案

您正在返回一个指向局部变量的指针。返回指针指向的迭代器在函数返回时已经被销毁。

你应该只按值返回,不要在这里为指针烦恼。迭代器很容易复制。

关于c++ - 指针不可从列表中取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22393016/

相关文章:

C#模仿Excel SLOPE函数

c - C 中查找数组中最大元素

c++ - 在函数中传递的指针的内存位置被删除

c++ - boost property_tree::json_parser::read_json 和 iostreams::filtering_streambuf

c++ - 如何在 boost::unordered_map 中使用自定义类型的键?

Android StateListDrawable 在 MultiTouch 之后保持按下状态

java - 对已排序的列表进行排序时,列表迭代在 Java 8 中抛出 ConcurrentModificationException

c++ - '登录': identifier not found

c++ - int() 在 C++ 中做什么?

c - 关闭文件时出现 Segmentation Fault 错误