我是 c++ 的新手,最近我尝试了以下操作:
list<Someclass> listofobjects;
int Index;
cin >> Index;
Someclass anobject = listofobjects[Index];
作为输出,我收到以下错误:
../src/Kasse.h:98:71: error: no match for ‘operator[]’ in ‘((Someclass*)this)->Someclass::listofobjects[((Someclass*)this)->Someclass::Index]’
有人知道为什么吗?我只是找不到解决方案...
提前致谢
std::list
是一个双向链表 - 它允许您从头或尾遍历它,但不允许随机访问特定索引。
如果你想要那样,也许你想要一个像 std::vector
这样的随机访问容器,一个动态数组。您需要确保它足够大以包含您需要的索引:
if (Index >= listofobjects.size()) {
listofobjects.resize(Index+1);
}
如果要修改它,您可能需要对列表中对象的引用,而不是拷贝:
Someclass & anobject = listofobjects[Index];
或者,如果您想要一个只包含您实际使用的索引对象的稀疏数组,您可以使用关联映射:
std::map<int, Someclass> objects;
Someclass & anobject = objects[Index];