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

Recommended Answers

All 7 Replies

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.

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

Try returning *temp, instead of temp.

I tried that too,the same

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

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.