First, lets be clear about one thing: if you need to access container elements by index, then you shouldn't use a list! There is no index operator for
std::list
, because it simply doesn't make sense!
Think about your use cases, i. e. what, exactly you want to do with your container: how you create it, how you modify it over time, how you access elements, etc.. Then consider whether there is really any situation where you want really just one specific element and the only suitable way to access that element would be through an index (note that there are alternate ways, e. g. you could store an iterator rather than an index!) Most of the time, you never need an index. And if you do,
std::vector
is very probably a much better choice.
Second, you can extend an existing class by deriving your own class from it. E. g. the following code compiles:
template <class T>
class mylist : public std::list<T> {
public:
T operator[](int i) const {
return front(); }
T& operator[](int i) {
return front(); }
};
void foo_list_index() {
mylist<int> l;
int x = 3;
l.push_back(2);
l.push_back(5);
int y = l[1];
l[0] = x;
}
Note however that, depending on the class you derive from, your class may unintentionally hide certain features of the base class - most notably constructors. So if you are planning to go that route you better spend some time learning about the base class' constructors and how to create appropriate 'overrides' in your derived class.