找不到 C++ 映射 [] 运算符
c++ Map [] operator not found
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:这是晚餐的东西。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 由于没有使用赋值运算符,映射的值是如何初始化的?
- 映射迭代器与运算符不匹配
- 在映射中使用结构作为键,忽略 == 运算符,误报
- c++:复制、删除和运算符=在原始指针映射中
- 在结构的嵌套映射上链接运算符 []
- 为什么 c++ 映射的运算符<不适用于 <=
- 写入/读取 std::映射到二进制文件需要运算符
- C++ STL 比较映射找不到(运算符==)
- 错误:尝试在两个映射中插入时,"__x < __y"中的"运算符<"不匹配
- 从运算符[]返回对映射的char*的引用
- std::映射运算符[]--未定义的行为
- 为什么我不能迭代这个 C++ 映射?出现错误,例如我无法使用<运算符
- 重载 [ ] 运算符用于 C++ 中的 stl 映射
- 是否可以使用运算符作为映射中的映射值
- 无序映射中运算符[]的C++专门化
- 没有用于引用映射的可行重载运算符
- 在映射中插入地址时,新运算符重载会导致无限递归
- 标准:映射与运算符=不匹配