0

I'm new to c++, and recently I tried the following:

list<Someclass> listofobjects;
int Index;
cin >> Index;
Someclass anobject = listofobjects[Index];

As an output I get the following error:

../src/Kasse.h:98:71: error: no match for ‘operator[]’ in ‘((Someclass*)this)->Someclass::listofobjects[((Someclass*)this)->Someclass::Index]’

Does anyone know why? I just can't find a solution for this... Thanks in advance

  • show the code declaring `listofobjects` an `Index`, now we can only guess what goes on – stijn Jan 21 '14 at 12:40
  • its in a class, but I've added the colums in the question, the list gets filled in the constructor of a class... – RandomDisplayName Jan 21 '14 at 12:43
  • 2
    std::list has no operator []: http://en.cppreference.com/w/cpp/container/list and http://stackoverflow.com/questions/1112724/why-isnt-there-an-operator-for-a-stdlist - you need eg vector if you want indexing (also that index should not be an `int` but a `size_t`) – stijn Jan 21 '14 at 12:44
  • QList has [] operator :) http://qt-project.org/doc/qt-5.0/qtcore/qlist.html – otisonoza Jan 21 '14 at 12:49
  • @otisonoza: Indeed, `QList` is closer to `std::deque` than `std::list`. `QLinkedList` is more like `std::list`. But this question is (presumably) about the standard library. – Mike Seymour Jan 21 '14 at 12:54

1 Answers1

2

std::list is a doubly linked list - it allows you to iterate through it from the beginning or end, but doesn't allow random access to a particular index.

If you want that, perhaps you want a random-access container like std::vector, a dynamic array. You'll need to make sure it's large enough to contain the index you need:

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

and you probably want a reference to the object in the list, not a copy, if you want to modify it:

Someclass & anobject = listofobjects[Index];

Alternatively, if you want a sparse array that only contains objects for the indices you actually use, you could use an associative map:

std::map<int, Someclass> objects;
Someclass & anobject = objects[Index];
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644