Hello. Can anyone help me how to implement the subscript ([]) operator for a STL list class ?

T& operator [] (int n)
{
		
}
template <typename T>

class list

{
public:
	struct node

	{

		T data;

		node* prev;

		node* next;

		node(T t, node* p, node* n) : data(t), prev(p), next(n) {}

	};

	node* head;

	node* tail;

public:

	class Iterator;
	friend class Iterator;

	list() : head( NULL ), tail ( NULL ) {}

...................................................................

i dont know what to return

bool flag=false;
node *temp = head;
for(int i=0;(temp!=NULL) && i<n;i++, temp=temp->next)
{
    if(i==n)
    {
      flag =true;
      break;
    }
}
if(flag)
  return temp;
else 
  return NULL;

If you keep a track of your elements, your double-linked list can index faster by searching from either head or tail by comparing n<Max/2.

Edited 6 Years Ago by nbaztec: n/a

Thanx for helping but i get some errors on line 12 and 14 on your code:

.\src\list.h:90: error: invalid initialization of reference of type 'Persoana&' from expression of type 'list<Persoana>::node*'
..\src\list.h:92: error: invalid initialization of non-const reference of type 'Persoana&' from a temporary of type 'int'

ps: Persoana its a class

What exactly is ur code? The operator [] should return the node at the index & not the reference to Template T.

Edited 6 Years Ago by nbaztec: n/a

I changed now so that the operator returns node& and teh function returns *temp,but still getting that error an returning NULL :

invalid initialization of non-const reference of type 'list<Persoana>::node&' from a temporary of type 'int'

Don't return a reference but a pointer. (temp)

node * operator(int Index)
{
.
.
return temp;
}
This article has been dead for over six months. Start a new discussion instead.