Couple of Things In Doubly Linked List Template
-
13-11-2019 - |
質問
I have a code of doubly Linked list and there are few lines of that code which idea is not clear . I request for experts comments on the lines which have comment in the following .Its long since I last time used C++ . There are just two line which i indicated are not understandable for me.
template <typename T>
class double_linked
{
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:
double_linked() : head( NULL ), tail ( NULL ) {}
template<int N>
double_linked( T (&arr) [N]) : head( NULL ), tail ( NULL )
{
for( int i(0); i != N; ++i)
push_back(arr[i]);
}
bool empty() const { return ( !head || !tail ); } // this doing?
operator bool() const { return !empty(); } // this doing? i know operators need in C++ but dont know the use of it here
void push_back(T);
void push_front(T);
T pop_back();
T pop_front();
~double_linked()
{
while(head)
{
node* temp(head);
head=head->next;
delete temp;
}
}
};
解決
operator bool() const
is a conversion operator. If an instance of double_linked
is used in a context where a bool is required, this function will be called to do the conversion. (And will evaluate to true
if the list is not empty in your case.)
The other function is a plain old function, which will return true
if either head
or tail
is null.
For more about conversion operators, see: How do conversion operators work in C++?
他のヒント
The first is a function to determine if the list is empty. In a doubly linked list, if you have at least one element then the head
and tail
pointers (which point to the start and the end of the list respectively) must point to a valid element. Therefore, you can test whether the list is empty by testing if both those pointers do not point to a valid element (i.e. are null
). That is what the expression !head || !tail
does - checks if either pointer is null
, and if so the list is empty.
The operator bool()
thing is a conversion operator. It basically means, whenever the list is cast to bool
, that function is called and the result used as the value of the bool
. The function returns whether the list is not empty, so an expression like bool result = myList;
will make result
be true
if the list is not empty.
This is a predicate telling us if it is empty or not, it is checking if the pointers are 0 (null).
bool empty() const { return ( !head || !tail ); } // this doing?
This allows the user to treat a instantiation of the container as a boolean, which is true if it is not empty.
operator bool() const { return !empty(); } // this
Implemented a linked list is a good programming excercise but if you want to use a linked list in your actual code then you should really use std::list (in ).