【问题标题】:c++: getting an object from a list by index doesnt work? [duplicate]c++:通过索引从列表中获取对象不起作用? [复制]
【发布时间】:2014-02-11 01:27:44
【问题描述】:

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

有人知道为什么吗?我只是找不到解决方案... 提前致谢

【问题讨论】:

  • 显示声明listofobjectsIndex的代码,现在我们只能猜测发生了什么
  • 它在一个类中,但我在问题中添加了列,列表被填充到类的构造函数中......
  • std::list has no operator []: en.cppreference.com/w/cpp/container/list and stackoverflow.com/questions/1112724/… - 如果你想要索引,你需要例如向量(而且该索引不应该是int,而是size_t )
  • @otisonoza:确实,QListstd::list 更接近std::dequeQLinkedList 更像std::list。但是这个问题(大概)是关于标准库的。

标签: c++ list class oop object


【解决方案1】:

std::list 是一个双向链表 - 它允许您从头或尾遍历它,但不允许随机访问特定索引。

如果你想要这样,也许你想要一个像std::vector 这样的随机访问容器,一个动态数组。您需要确保它足够大以包含您需要的索引:

if (Index >= listofobjects.size()) {
    listofobjects.resize(Index+1);
}

如果你想修改它,你可能想要引用列表中的对象,而不是副本:

Someclass & anobject = listofobjects[Index];

或者,如果您想要一个仅包含您实际使用的索引的对象的 sparse 数组,您可以使用关联映射:

std::map<int, Someclass> objects;
Someclass & anobject = objects[Index];

【讨论】:

  • 感谢您的回答,我现在使用 std::vector :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 2018-01-07
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多