找不到 C++ 映射 [] 运算符

c++ Map [] operator not found

本文关键字:运算符 映射 C++ 找不到      更新时间:2023-10-16
void Library::addKeywordsForItem(const Item* const item, int nKeywords, ...)
{
    // the code in this function demonstrates how to handle a vararg in C++
    va_list     keywords;
    char        *keyword;
    va_start(keywords, nKeywords);
    for (int i = 0; i < nKeywords; i++)
    {
        keyword = va_arg(keywords, char*);
        ((Item*)const_cast<Item*>(item))->addKeyword(string(keyword)); 
        ItemSet* itemSet = keywordItems[string(keyword)];
        if (itemSet == NULL)
        {
            itemSet = new ItemSet();
            keywordItems[keyword] = itemSet;
        }
        bool isNull = (itemSet == NULL) ? true : false;
        itemSet->insert(((Item*)const_cast<Item*>(item)));
    }
    va_end(keywords);
}
const ItemSet* Library::itemsForKeyword(const string& keyword) const
{
    return keywordItems[((string)const_cast<string&>(keyword))];
}

在上面的代码中,第一种方法按预期工作。第二种方法没有,并显示错误@"[">

没有运算符 "[]" 匹配这些操作数 操作数类型为: 常量 StringToItemSetMap [ std::string ]

StringToItemSetMap 只是 map 的一个类型定义。我尝试了不同的转换,并创建了一个局部字符串变量,但没有运气。甚至像关键字项目[字符串("测试"(];在第二种方法中不起作用,但在第一种方法中有效。我可能错过了什么吗?

编辑:

const ItemSet* Library::itemsForKeyword(const string& keyword) const
{
    std::map<std::string, ItemSet*>::const_iterator it = keywordItems.find(keyword);
    if (it != keywordItems.end())
    {
        return it->second;
    }
    return NULL;
}

正如在答案中指出的那样,问题在于第二种方法是常量,而map::operator[]不是。

您正在使用被覆盖的operator[],它必须对基础映射具有非常量访问权限,因为如果请求的键位置不存在一个新条目,它将添加一个新条目。在您的情况下,这将添加一个 NULL 指针(不讨论原因(。您的成员函数被声明为 const ,因此映射不可修改。

将映射声明为 mutable(不推荐(,或者使用迭代器搜索并在搜索返回 NULL 时返回 NULL,如果搜索返回keywordItems.end() 。否则,返回迭代器的对象(以 it->second 为单位(。

const ItemSet* Library::itemsForKeyword(const string& keyword) const
{
    std::map<std::string, ItemSet*>::const_iterator it =  keywordItems.find(keyword);
    if (it != keywordItems.cend())
       return it->second;
    return nullptr;
}

注意:我强烈建议使用直接对象,或者至少使用智能指针(例如std::shared_ptr<ItemSet>(来获取地图对象内容。RAII:这是晚餐的东西。