Implementing a double linked list that can have different types of variables in one list.
Example) 11 <-> "aa" <-> 'A' <-> 1.2345
I'm trying to return the value stored in the nth of the list through the get(intn) function without defining the type of the function in the main, but it didn't work out well, so I'm posting to ask for your help ㅠ<
.hpp file
class node_base{
public:
node_base *next;
node_base *prev;
node_base () { next = 0; prev = 0; }
virtual void print () = 0;
virtual int get_node_size () = 0;
};
template <typename T>
class node : public node_base{
public:
T data;
node (const T& val) : data(val) {}
virtual void print (){ cout << data << " "; }
virtual int get_node_size () { return sizeof (data); }
T getData () { return data; }
};
class unvlist{
node_base *head;
public:
int len;
unvlist ();
void print () {
node_base *h = head;
while (h->next != NULL){
h->print ();
h = h->next;
}
h->print ();
}
template <typename T> unvlist (const T* arr, int n);
~unvlist ();
//operator +
//operator ==
template <typename T> void set (int n, const T& val);
template <typename T> T get (int n);
template <typename T> T insert (int n, const T& val);
void erase (int n);
int size ();
void pop_back ();
void pop_front ();
template <typename T> void push_back (const T& val);
template <typename T> void push_front (const T& val);
};
/* get function: Returns the value stored in the nth in the list. */
template <typename T>
T unvlist :: get (int n){
T retval;
if (n >= len || n < 0){
cout << "'In unvlist::get'-> Out of Bound!!!" << endl;
return 0;
}
if (n >= 0){
node_base *h = head;
for (int i = 0; i < n; i++) { h = h->next; }
retval = static_cast<node<T>*>(h)->getData ();
}
return retval;
}
main.cpp file
int main(){
unvlist *l1 = new unvlist ();
l1->push_back<string> ("aa");
l1->push_back<char> ('A');
l1->push_back<float> (1.2345);
l1->push_front<int> (11);
for (int i = 0; i < 4; i++){
output all values in cout <<<l1->get(i) <<"; // list
} } cout << endl;
return 0;
}
compile error
c++ template
template <typename T> T get (int n);
Instead, the return type is implemented as a node, and
node get(int n);
How about overriding operator << in node (or node_base)?
578 Understanding How to Configure Google API Key
610 GDB gets version error when attempting to debug with the Presense SDK (IDE)
914 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.