2

所以我有一个 std::unordered_map,我想访问存储在这个地图中的字符串。我想搜索 intro 地图内的所有单词并与给定单词进行比较。如果字符串相同,则继续执行 if 语句。

{
public:    
    bool CheckFoo(const char* word);

protected:
    typedef std::unordered_map<std::string, bool> word_map;
    word_map words_map;
};

bool CheckFoo(const char* word)
{
    if (words_map.empty())
    {
        return false;
    }

    auto it = words_map.begin();

    while (it != words_map.end())
    {
        const std::string &r = it->first;
        const char* tmp = word;

        if (strcmp(tmp, r.c_str() ) == 0)
        {
            return true;
        }
    }

    return false;
}

if (    CheckFoo("wordFoo") )
{
    //  bla bla
}

问题是这些代码会生成一个 .core 转储文件。您在我的代码中看到任何错误吗?

崩溃核心分析将我指向 strcmp 行

4

2 回答 2

3

还不能写评论,但是,

就像 Nunchy 写的那样, tmp 没有在那个上下文中定义。我还注意到您的代码从不增加映射迭代器,这将导致一个永无止境的循环。

我假设您没有将实际代码复制到您的帖子中,而是匆忙重写了它,这导致了一些拼写错误,但如果不是,请尝试确保您在调用 strcmp 时使用的是temp而不是tmp,并确保循环实际上增加了迭代器。

就像您帖子中的一条评论指出的那样,请确保地图中确实有数据和函数参数。

于 2018-11-22T00:20:56.200 回答
0

您声明temp然后引用tmp不存在的:

    const char* temp = word;

    if (strcmp(tmp, r.c_str() ) == 0)

这能编译吗?当然应该是:

    const char* temp = word;

    if (strcmp(temp, r.c_str() ) == 0)

?

于 2018-11-22T00:14:52.980 回答