c++:通过索引从列表中获取对象不起作用?

标签 c++ list class oop object

<分区>

我是 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];

关于c++:通过索引从列表中获取对象不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21258364/

相关文章:

c++ - 我可以使用 JsonCpp 部分验证 JSON 输入吗?

c++ - 获取 C++ RTTI 作为 switch 语句中调度的枚举

c# - Dictionary<string, List<IRp>> 问题,覆盖数据

python - 来自文本文件的字典

c# - 找不到 'Name' 的定义

C++ 类前向声明

c++ - 使用 boost::assign 和嵌套在 std::map 中的 std::set

c++ - 如何存储具有可能不同的 boost::dimension 的 boost::quantity

java - 使用 JAXB 解码列表

检查参数类型的 Pythonic 方法