Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to overload [index] for list in C++.
I want to use list, like below code.
C++
list<t> T;
t O;
O=T[1];
T[1]=O
Posted
Updated 19-Jul-15 21:33pm
v2
Comments
[no name] 20-Jul-15 3:56am    
You can't. std::list does not have subscripting access. Use std::vector
kave2011 20-Jul-15 3:58am    
don't exist no way??!!
because I need list instead of vector.
[no name] 20-Jul-15 4:02am    
You can't use what does not exist unless you create it yourself. http://stackoverflow.com/questions/1112724/why-isnt-there-an-operator-for-a-stdlist
Philippe Mori 20-Jul-15 13:08pm    
As already mentionned, it does not make much sense. You don't use a list if you want to access element by index. For large lists, it would be extremely innefficient.
kave2011 21-Jul-15 15:31pm    
sure

1 solution

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:
C++
template <class T>
class mylist : public std::list<T> {
public:
   T operator[](int i) const {
      return front();//replace with actual code
   }
   T& operator[](int i) {
      return front();//replace with actual code
   }
};
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.
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 20-Jul-15 5:57am    
Good answer, +5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900