How can I implement for_each for that implementation of Node and List?
I'm sure it's not long code, can some share a few strokes of his knowledge please? Do I need to implement it as template or just as inner function.
Thanks for helping.
class Node {
int data;
Node *next;
public:
Node() {}
void SetData(int aData) { data = aData; }
void SetNext(Node *aNext) {
next = aNext;
}
int Data() { return data; }
Node* Next() { return next; }
};
// List class
class List {
Node *head;
public:
List() { head = nullptr; }
void Append(int data){
// Create a new node
Node *newNode = new Node();
newNode->SetData(data);
newNode->SetNext(nullptr);
// Create a temp pointer
Node *tmp = head;
if ( tmp != nullptr ) {
// Nodes already present in the list
// Parse to end of list
while ( tmp->Next() != nullptr) {
tmp = tmp->Next();
}
// Point the last node to the new node
tmp->SetNext(newNode);
}
else {
// First node in the list
head = newNode;
}
}
void Delete(int data){
// Create a temp pointer
Node *tmp = head;
// No nodes
if ( tmp == nullptr ) return;
// Last node of the list
if ( tmp->Next() == nullptr ) {
delete tmp;
head = nullptr;
}
else {
// Parse thru the nodes
Node* prev;
do {
if ( tmp->Data() == data ) break;
prev = tmp;
tmp = tmp->Next();
} while ( tmp != nullptr );
// Adjust the pointers
if (tmp->Next()!=nullptr) prev->SetNext(tmp->Next());
else prev->SetNext(nullptr);
// Delete the current node
if (tmp!=nullptr) delete tmp;
}
}
};
EDIT:
This is use of iterator:
for (List<Pair, CompareFunction>::myIterator it = this->_pairs.begin();
it != this->_pairs.end(); ++it) {
Pair cur_pair = *it;
if (cur_pair.first == key) {
this->_pairs.Delete(cur_pair);
this->_size--;
}
}
This is Pair Class as sub-class in another template class:
template <class KeyType, class ValueType, class CompareFunction = std::less<KeyType> >
class MtmMap {
public:
class Pair {
public:
Pair():first(KeyType()){} ////////////////////
Pair(const KeyType& key, const ValueType& value)
: first(key), second(value) {}
const KeyType first;
ValueType second;
~Pair() = default;
In our concrete case KeyType and ValueType run as both int.
Add the following code into your List class:
class List{
...
class myIterator
{
public:
typedef myIterator self_type;
typedef Node* pointer;
myIterator(pointer ptr) : ptr_(ptr) { }
self_type operator++() {
self_type i = *this;
if (ptr_) ptr_ = ptr_->Next();
return i;
}
int operator*() { if (ptr_ ) return ptr_->Data(); else return 0; }
bool operator==(const self_type& rhs) {
if (!ptr_ && !rhs.ptr_) return true;
return (ptr_ && rhs.ptr_ && rhs.ptr_->Data()==ptr_->Data());
}
bool operator!=(const self_type& rhs) {
return !(*this==rhs);
}
private:
pointer ptr_ = nullptr;
};
myIterator begin() { return myIterator(head); }
myIterator end() { return myIterator(nullptr); }
};
You may then use normal iterators like in the following example:
List l;
l.Append(2);
l.Append(5);
l.Append(7);
l.Append(11);
for (int i: l) std::cout << i << std::endl;
//or
for (myIterator it=l.begin(); it!=l.end(); ++it) std::cout << *it << std::endl;
Related
I am trying to write a playlist method for songs in c++, however, I keep running into frequent errors.
template <typename T>
struct cir_list_node
{
T* data;
cir_list_node *next, *prev;
//destructor
~cir_list_node() {
delete data;
}
};
template <typename T>
struct cir_list
{
public:
using node = cir_list_node<T>; // renaiming for local use
using node_ptr = node*;
private:
node_ptr head;
size_t n;
public:
// basic constructor and size function
cir_list(): n(0) // initiator list
{
head = new node(NULL,NULL,NULL); //dummy node
head->next = head; // circular list wraps around
head->prev = head;
}
cir_list(const cir_list& other): cir_list()
{
// insert in reverse order (okay because list is circular)
for(const auto& i : other)
insert(i);
}
cir_list(const std::initializer_list<T>& il): head(NULL), n(0)
{
//insert in reverse order
for(const auto& i : il)
insert(i);
}
~cir_list()
{
while(size())
{
erase(head->data);
}
}
size_t size() const
{
return n;
}
void insert(const T& value)
{
node_ptr newNode = new node(new T(value),NULL,NULL);
n++;
auto dummy = head->prev;
dummy->next = newNode;
newNode->prev = dummy;
if(head == dummy) {
dummy->prev = newNode;
newNode->next = dummy;
head = newNode;
return;
}
newNode->next = head;
head->prev = newNode;
head = newNode;
return;
}
void erase(const T& value)
{
auto cur = head, dummy = head->prev;
while (cur != dummy){
if(*(cur->data) == value){
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
if(cur == head)
head = head->next;
delete cur;
n--;
return;
}
cur = cur->next;
}
}
struct cir_list_it
{
private:
node_ptr ptr;
public:
cir_list_it(node_ptr p) : ptr(p)
{}
T& operator*()
{
return *(ptr->data);
}
node_ptr get()
{
return ptr;
}
cir_list_it& operator++() // prefix
{
ptr = ptr->next;
return *this;
}
cir_list_it operator++(int) // postfix
{
cir_list_it it = *this;
++(*this);
}
cir_list_it& operator--() //prefix
{
ptr = ptr->prev;
return *this;
}
cir_list_it operator--(int) // postfix
{
cir_list_it it = *this;
--(*this);
return it;
}
friend bool operator == (const cir_list_it& it1, const cir_list_it& it2)
{
return it1.ptr == it2.ptr;
}
friend bool operator != (const cir_list_it& it1, const cir_list_it& it2)
{
return it1.ptr != it2.ptr;
}
};
cir_list_it begin()
{
return cir_list_it {head};
}
cir_list_it end()
{
return cir_list_it {head->prev};
}
cir_list_it end() const
{
return cir_list_it{head->prev};
}
};
struct playlist
{
cir_list<int> list;
void insert(int song)
{
list.insert(song);
}
void erase(int song)
{
list.erase(song);
}
void loopOnce()
{
for(auto& song : list){
std::cout << song << " ";
}
std::cout << std::endl;
}
};
int main()
{
playlist pl;
pl.insert(1);
pl.insert(2);
std::cout << "Playlist: ";
pl.loopOnce();
playlist pl2 = pl;
pl2.erase(2);
pl2.insert(3);
std::cout << "Second playlist";
pl2.loopOnce();
}
Errors
1 and 2:
3 and 4:
It seems there is a typo
struct cir_list_node
{
T* data;
cir_list_node *next, *prev;
//destructor
~cir_list_node() {
delete data;
}
};
You forgot to prefix this declaration with
template <typename T>
This template structure declaration declares an aggregate.
You can not initialized it with an expression inside parentheses like
head = new node(NULL,NULL,NULL);
Instead you need to write using braces
head = new node { NULL, NULL, NULL };
or as you are writing a C++ program then
head = new node { nullptr, nullptr, nullptr };
It seems there is a typo
struct cir_list_node
{
T* data;
cir_list_node *next, *prev;
//destructor
~cir_list_node() {
delete data;
}
};
I have a Doubly linked List class wherein i have a function which uses my classes iterators to loop over the collection. However in 1 specific place it runs for an extra loop and I cannot figure out why.
current merge template
template <typename T>
void DlList<T>::merge(SortedList& other) {
iterator it = back_->prev_;
iterator oit = other.begin();
while (oit.current_->next_ != NULL) {
std::cout << *it << " " << *oit << std::endl;
it.current_->next_ = oit.current_;
back_->prev_ = oit.current_;
//back_->prev_->next_ = back_;
//other.back_->prev_ = other.back_->prev_->prev_;
it++;
oit++;
}
}
It always iterates and extra time and added a null node to the list and I don't understand why.
Any insight is greatly appricicated!
Edit Added full project examples to explain intention of function
I am working on a templated data structure class which is a doubly linked list which uses sentinel nodes.
The list is sorted based on insert() and I am working on a merge function wherein the nodes of each list must be combined into this->list. The nodes must be moved and not have new ones created. and if the same value exists in both lists the other node value must come after the current node value.
I coded what I thought was a logical implementation however the output I get is not as expected and the results do not make sense to me, so if anyone could explain how i am getting the results I have it would be greatly appreciated.
Class Definition
class SortedList {
struct Node {
T data_;
Node* next_;
Node* prev_;
Node(const T& data = T{}, Node* nx = nullptr, Node* pr = nullptr) {
data_ = data;
next_ = nx;
prev_ = pr;
}
};
Node* front_;
Node* back_;
public:
class const_iterator {
friend class SortedList;
Node* current_;
const_iterator(Node* n)
{
current_ = n;
}
public:
const_iterator() {
//Set to safe state
current_ = nullptr;
}
const_iterator& operator++() {
current_ = current_->next_;
return *this;
}
const_iterator operator++(int) {
const_iterator old = *this;
current_ = current_->next_;
return old;
}
const_iterator& operator--() {
current_ = current_->prev_;
return *this;
}
const_iterator operator--(int) {
const_iterator old = *this;
current_ = current_->prev_;
return old;
}
bool operator==(const_iterator rhs) {
return (current_ == rhs.current_) ? true : false;
}
bool operator!=(const_iterator rhs) {
return !(*this == rhs);
}
bool operator>(const_iterator rhs) {
return current_->data_ > rhs->current_->data_;
}
const T& operator*()const {
return current_->data_;
}
};
class iterator :public const_iterator {
friend SortedList;
iterator(Node* n) :const_iterator(n) {};
public:
iterator() : const_iterator() {};
//prefix
iterator& operator++() {
this->current_ = this->current_->next_;
return *this;
}
//post-fix
iterator operator++(int) {
iterator old = *this;
this->current_ = this->current_->next_;
return old;
}
iterator& operator--() {
this->current_ = this->current_->prev_;
return *this;
}
iterator operator--(int) {
iterator old = *this;
this->current_ = this->current_->prev_;
return old;
}
T& operator*() {
return this->current_->data_;
}
const T& operator*()const {
return this->current_->data;
}
};
SortedList(); //done
~SortedList();
SortedList(const SortedList& rhs);
SortedList& operator=(const SortedList& rhs);
SortedList(SortedList&& rhs);
SortedList& operator=(SortedList&& rhs);
iterator begin() {
return iterator(front_->next_);
}
iterator end() {
return iterator(back_);
}
const_iterator cbegin() const {
return const_iterator(front_->next_);
}
const_iterator cend() const {
return const_iterator(back_);
}
iterator insert(const T& data);
iterator search(const T& data);
const_iterator search(const T& data) const;
iterator erase(iterator it);
void merge(SortedList& other);
bool empty() const;
int size() const;
};
first merge function attempt
template <typename T>
void SortedList<T>::merge(SortedList& other) {
iterator it = this->begin();
iterator oit = other.begin();
while (oit != other.end()) {
std::cout << *oit << " " << *it << std::endl;
if (*oit < *it) {
oit.current_->prev_->next_ = oit.current_->next_;
oit.current_->next_->prev_ = oit.current_->prev_;
oit.current_->next_ = it.current_;
oit.current_->prev_ = it.current_->prev_;
it.current_->next_ = oit.current_;
}
else {
oit.current_->prev_->next_ = oit.current_->next_;
oit.current_->next_->prev_ = oit.current_->prev_;
oit.current_->next_ = it.current_->next_;
oit.current_->prev_ = it.current_;
it.current_->prev_ = oit.current_;
}
oit++;
it++;
}
}
main tester
int main() {
int num[] = { 3,5,1,2,6,8,9,11 };
int num2[] = { 1,5,4,6,12,7,8,9 };
SortedList<int> l;
SortedList<int> l2;
for (int i = 0; i < 8; i++)
{
l.insert(num[i]);
l2.insert(num2[i]);
}
SortedList<int>::iterator result;
SortedList<int>::iterator result2 = l2.begin();
result = l.begin();
while (result != l.end()) {
std::cout << *result << " " << *result2 << std::endl;
++result;
++result2;
}
l.merge(l2);
output
1 1
2 4
3 5
5 6
6 7
8 8
9 9
11 12
1 1
2 2
3 3
5 5
6 6
8 8
9 9
11 11
0 0
I dont understand why my second output is showing same the same values for *it and *oit I am pretty certain the error is in how I assign the the oit.current_->next & prev but i am unsure.
any insight is appriciated.
You seem to want to merge two sorted doubly linked lists together. There are several problems with your approach, and so I'll show you my code:
#include <iostream>
using namespace std;
struct node {
node* next;
node* prev;
int val;
node(int i_val)
: next(nullptr),
prev(nullptr),
val(i_val)
{}
};
void connect(node* a, node* b) {
if (a != nullptr) {
if (a->next != nullptr) {
a->next->prev = nullptr;
}
a->next = b;
}
if (b != nullptr) {
if (b->prev != nullptr) {
b->prev->next = nullptr;
}
b->prev = a;
}
}
struct DlList {
node* first_node;
node* last_node;
DlList()
: first_node(nullptr),
last_node(nullptr)
{}
~DlList() {
for (node* n = first_node; n != nullptr; n = n->next) {
delete n->prev;
}
delete last_node;
}
void push(int new_val) {
node* new_node = new node(new_val);
connect(last_node, new_node);
last_node = new_node;
if (first_node == nullptr) {
first_node = new_node;
}
}
void merge_sorted(DlList& other) {
node* this_node = first_node;
node* other_node = other.first_node;
node* n = nullptr; // goes through each node of the new list in order
while (this_node != nullptr || other_node != nullptr) {
node* next_n;
if (other_node == nullptr ||
(this_node != nullptr && this_node->val <= other_node->val)) {
// entered if other_node is nullptr or this_node comes before other_node
next_n = this_node;
this_node = this_node->next;
}
else {
// entered if this_node is nullptr or other_node comes before this_node
next_n = other_node;
other_node = other_node->next;
}
connect(n, next_n);
if (n == nullptr) { // first time through loop
first_node = next_n;
}
n = next_n;
}
last_node = n;
// *this takes ownership of all of other's nodes
other.first_node = nullptr;
other.last_node = nullptr;
}
};
int main() {
std::cout << "running test" << std::endl;
int num[] = { 1,2,3,5,6,8,9,11 };
int num2[] = { 1,4,5,6,7,8,9,12 };
DlList l;
DlList l2;
for (int i = 0; i < 8; i++)
{
l.push(num[i]);
l2.push(num2[i]);
}
l.merge_sorted(l2);
for (node* n = l.first_node; n != nullptr; n = n->next) {
std::cout << n->val << " ";
}
std::cout << std::endl;
}
You may add iterators and other higher-level abstractions later, but for now I think they complicate and obscure the logic. I also did not see a need for a "past-the-end-of-the-list" node in your case, as nullptr would suffice. Though of course these could rather easily be added in if you wanted them to, just for demonstration purposes they are omitted.
Notice how I made a dedicated connect function that does all the pointer assignments as they should be done for two nodes. It handles a bunch of combinations of nullptr cases, too, so you don't need to worry as much about checking for null pointers outside of the function. (Note how the first time through the merge loop, a null n pointer is connected to next_n). Now you hardly need to worry about pointer assignments, and it's clearer when you just say, "connect these two nodes."
My merger function goes through each node in the newly created list. It picks the next node from the two available nodes, from *this and other. It then connects the current node to the next node, and advances the current node to the next node. It has special handling when one or the other of the lists runs out (this_node or other_node becomes nullptr), which indeed happens in the given test case. It takes care to assign first_node and last_node in the correct places, and to clear other after the merge, so as to prevent double ownership issues.
I am trying to implement a LinkedList which can be iterated through in c++.
I have therefore made an Iterator class, such that dereferencing an Iterator would return the first element. However, this has not been working. When I then instantiate a new int LinkedList and attempt to access the first element by dereferencing the result of begin(), I do not retrieve the first element of the list, but a 10 digit number such as '1453755360'
My node class is just composed of two right/left node pointers and a data variable
linkedlist class
template <typename T>
class LinkedList{
public:
LinkedList(){
count =(0);
head =(nullptr);
tail =(nullptr);
}
void push_head(T input){
Node<T> newNode = Node<T>(input);
newNode.left = nullptr;
newNode.right = head;
head = &newNode;
count++;
}
T front(){
T& data = (head->data);
return data;
}
void push_tail(T input){
Node<T> newNode = Node<T>(input);
newNode.right = tail;
newNode.left = nullptr;
tail = &newNode;
count++;
}
T back(){
T& data = (tail->data);
return data;
}
Iterator<T> begin(){
Iterator<T> test = Iterator<T>(head);
return test;
}
private:
int count;
Node<T> *head;
Node<T> *tail;
};
Here is where I am testing the code
LinkedList<int> ll;
ll.push_tail(7);
ll.push_tail(9);
if (*(ll.begin()) == 9) {
cout << "pass" << endl;
} else {
cout << "returned : " << *(ll.begin()) << endl;
}
The push_back() implementation requires that if head is null it has to be set, the same for the push_front with respect to the tail.
You are allocating your node objects on the stack, so they are destroyed automatically when they go out of scope. You are storing pointers to those objects, which leaves the pointers dangling when the objects are destroyed. You need to allocate the nodes on the heap using new instead.
Also, push_front() is not updating tail when the list is empty, and is not updating an existing head to point at the new node when the list is not empty. Similar with push_back().
Try something more like this:
template <typename T>
struct Node
{
T data;
Node *left;
Node *right;
Node(const T &d = T(), Node *l = nullptr, Node *r = nullptr)
: data(d), left(l), right(r) {}
};
template <typename T>
class NodeIterator {
public:
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef std::bidirectional_iterator_tag iterator_category;
NodeIterator(Node<T> *input = nullptr) : cur(input) {}
NodeIterator(const NodeIterator &) = default;
NodeIterator(NodeIterator &&) = default;
~NodeIterator() = default;
NodeIterator& operator=(const NodeIterator &) = default;
NodeIterator& operator=(NodeIterator &&) = default;
reference operator*() {
return cur->data;
}
NodeIterator& operator++ () {
if (cur) cur = cur->right;
return *this;
}
NodeIterator operator++ (int) {
NodeIterator tmp(*this);
if (cur) cur = cur->right;
return tmp;
}
NodeIterator& operator-- () {
if (cur) cur = cur->left;
return *this;
}
NodeIterator operator-- (int) {
NodeIterator tmp(*this);
if (cur) cur = cur->left;
return tmp;
}
bool operator==(const NodeIterator &rhs) const {
return (rhs.cur == cur);
}
bool operator!=(const NodeIterator &rhs) const {
return (rhs.cur != cur);
}
private:
Node<T> *cur;
};
template <typename T>
class LinkedList {
public:
typedef NodeIterator<T> iterator;
LinkedList() : count(0), head(nullptr), tail(nullptr) {}
~LinkedList() {
while (head) {
Node<T> *tmp = head;
head = head->right;
delete tmp;
}
}
void push_front(const T &input) {
Node<T> *newNode = new Node<T>(input, nullptr, head);
if (head) head->left = newNode;
head = newNode;
if (!tail) tail = newNode;
++count;
}
T& front() {
return head->data;
}
void push_back(const T &input) {
Node<T> *newNode = new Node<T>(input, tail, nullptr);
if (!head) head = newNode;
if (tail) tail->right = newNode;
tail = newNode;
++count;
}
T& back() {
return tail->data;
}
iterator begin() {
return iterator(head);
}
iterator end() {
return iterator();
}
private:
int count;
Node<T> *head;
Node<T> *tail;
};
Then you can do this:
LinkedList<int> ll;
ll.push_back(7);
ll.push_back(9);
auto iter = ll.begin();
if (*iter == 7) {
cout << "pass" << endl;
} else {
cout << "returned : " << *iter << endl;
}
You can even do things like this now:
for (LinkedList<int>::iterator iter = ll.begin(), end = ll.end(); iter != end; ++iter) {
cout << *iter << endl;
}
for (int i : ll) {
cout << i << endl;
}
I am trying to implement a linked list, and I am completely lost. I'm getting break points all over the place, specifically with the erase method. Whenever I alter the erase method, some error will inevitably spring up. I've got pointer errors, problems with the destructor that only occur when the erase method is called, and so on.
Here's what I have so far:
Header file:
#pragma once
class IntList {
private:
class IntNode {
public:
IntNode(int v, IntNode *pr, IntNode *nx);
~IntNode();
IntNode* previous;
IntNode* next;
class iterator {
public:
iterator(IntNode* t);
int& operator*();
iterator& operator++();
iterator& operator--();
bool operator!=(iterator other)const;
private:
IntNode* target;
};
private:
int value;
};
IntNode* head;
IntNode* tail;
int count;
public:
IntList();
~IntList();
void push_back(int v);
void pop_back();
int size() const { return count; }
typedef IntNode::iterator iterator;
iterator begin();
iterator end();
//unsigned int size() const;
void push_front(int value);
bool empty() const;
int& front();
int& back();
void clear();
iterator erase(iterator position);
};
Implementation:
#include "IntList.h"
#include <stdexcept>
IntList::IntList() : head{ nullptr }, tail{ nullptr }, count{ 0 }
{}
IntList::~IntList() {
while (head) {
head = head->next;
delete head;
}
}
void IntList::push_back(int v) {
tail = new IntNode{ v, tail, nullptr };
if (!head) { head = tail; }
count += 1;
}
void IntList::pop_back() {
tail = tail->previous;
delete tail->next;
count -= 1;
}
IntList::iterator IntList::begin()
{
return iterator{ head };
}
IntList::iterator IntList::end() {
return iterator{ nullptr };
}
void IntList::push_front(int value) {
head = new IntNode{ value, nullptr, head };
if (!tail) { tail = head; }
count += 1;
}
bool IntList::empty() const{
return (count==0);
}
int& IntList::front() {
return *begin();
}
int& IntList::back() {
return *begin();
}
void IntList::clear() {
head = nullptr;
tail = nullptr;
count = 0;
}
IntList::iterator IntList::erase(iterator position) {
int midpointL = 0;
for (iterator index = begin(); index != position; ++index) {
midpointL++;
}
if (midpointL == 0) {
head = head->next;
}
else if (midpointL == count) {
tail = tail->previous;
}
else {
// Move head to get a reference to the component that needs to be deleted
for (int i = 0; i < midpointL; i++) {
head = head->next;
}
// Change the previous and next pointers to point to each other
(head->previous)->next = (head->next);
(head->next)->previous = (head->previous);
for (int i = midpointL-1; i > 0; i++) {
head = head->previous;
}
}
count-=1;
return position;
}
IntList::IntNode::IntNode(int v, IntNode * pr, IntNode * nx)
: previous{ pr }, next{ nx }, value{ v }
{
if (previous) { previous->next = this; }
if (next) { next->previous = this; }
}
IntList::IntNode::~IntNode() {
if (previous) previous->next = next;
if (next) next->previous = previous;
}
IntList::IntNode::iterator::iterator(IntNode* t)
: target{ t }
{}
int& IntList::IntNode::iterator::operator*() {
if (!target) { throw std::runtime_error{ "Deferenced sentinel iterator." }; }
return target->value;
}
IntList::IntNode::iterator& IntList::IntNode::iterator::operator++()
{
if (target) { target = target->next; }
return *this;
}
IntList::IntNode::iterator& IntList::IntNode::iterator::operator--()
{
if (target) { target = target->previous; }
return *this;
}
bool IntList::IntNode::iterator::operator!=(iterator other)const
{
return (!(target == other.target));
}
Could anyone help point me in the right direction?
Thanks!
Let's make a kind of quick review here:
IntList::~IntList() {
while (head) {
head = head->next;
delete head;
}
}
you should do instead:
IntList::~IntList() {
while (head) {
IntNode* newHead = head->next;
delete head;
head = newHead;
}
}
as you are deleting the "next" object and then you are trying to get access to it in the next iteration.
void IntList::pop_back() {
tail = tail->previous;
delete tail->next;
count -= 1;
}
Here you are not checking if tail is null or if it is pointing to head..(what's the empty condition?), maybe count!=0? in case you may delete a not existing next-node
IntList::iterator IntList::end() {
return iterator{ nullptr };
}
..end is null? ebd should be your tail...
int& IntList::back() {
return *begin();
}
that's begin..not back.
void IntList::clear() {
head = nullptr;
tail = nullptr;
count = 0;
}
a clear should release all the objects in the list. You are generating garbage here (leaks).
I stopped here, sorry for that, it's just a coffee break. But you should look carefully at:
* null pointer usage
* delete your node list item when not needed
* pay attention to do not use invalid pointers (like head->previous->next I saw somewhere)
You have to review your code, bottom up. Hope that those first hints help you through your learning process.
Have fun,
Ste
For academic purposes, I'm trying to develop a little "textual adventure game". I have to implement all data structures by my own. Now, I have some problems with the implementation of a generic (template) LinkedList.
In the specific, this data structure works with everything (primitive data types and custom objects) BUT strings! (standard library strings).
When I try to add strings to a list, the application crashes with the following error (in console):
"terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_constructor null not valid"
The list is implemented as a "double linked list" using the head-node as first-last node
Here the code ("Abstract" List interface):
#ifndef LIST_H_
#define LIST_H_
template <class T>
class List
{
public:
virtual ~List() {}
virtual T get(int position) = 0;
virtual List* add(T item) = 0;
virtual List* insert(T item, int position) = 0;
virtual List* remove(int position) = 0;
virtual int size() const = 0;
virtual bool isEmpty() const = 0;
protected:
private:
};
#endif /* LIST_H_ */
This is the LinkedList implementation (the "node" class):
#include "List.h"
#include <stdlib.h>
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
template <class T>
class ListNode
{
public:
ListNode(T item)
{
mItem = item;
mNext = NULL;
mPrev = NULL;
}
ListNode(T item, ListNode<T>* next, ListNode<T>* prev)
{
mItem = item;
mNext = next;
mPrev = prev;
}
~ListNode()
{
delete &mItem;
}
T getItem()
{
return mItem;
}
ListNode<T>* getNext()
{
return mNext;
}
ListNode<T>* getPrev()
{
return mPrev;
}
void setItem(T item)
{
mItem = item;
}
void setNext(ListNode<T>* next)
{
mNext = next;
}
void setPrev(ListNode<T>* prev)
{
mPrev = prev;
}
protected:
private:
T mItem;
ListNode<T> *mNext, *mPrev;
};
The LinkedList class:
template <class K>
class LinkedList : public List<K>
{
public:
LinkedList()
{
mSize = 0;
mFirstNode = NULL;
}
~LinkedList()
{
// implementazione distruttore tramite ciclo sui nodi
}
K get(int position)
{
K item = NULL;
ListNode<K>* targetNode = getNodeAtPosition(position);
if (targetNode != NULL) item = targetNode->getItem();
return item;
}
List<K>* add(K item)
{
if (mFirstNode == NULL)
{
mFirstNode = new ListNode<K>(item);
mFirstNode->setNext(mFirstNode);
mFirstNode->setPrev(mFirstNode);
}
else
{
ListNode<K>* newNode = new ListNode<K>(item, mFirstNode, mFirstNode->getPrev());
mFirstNode->getPrev()->setNext(newNode);
mFirstNode->setPrev(newNode);
}
mSize++;
return this;
}
List<K>* insert(K item, int position)
{
ListNode<K>* targetNode = getNodeAtPosition(position);
if (targetNode != NULL)
{
ListNode<K>* newNode = new ListNode<K>(targetNode->getItem(), targetNode->getNext(), targetNode);
targetNode->setItem(item);
targetNode->setNext(newNode);
mSize++;
}
return this;
}
List<K>* remove(int position)
{
ListNode<K>* targetNode = getNodeAtPosition(position);
if (targetNode != NULL)
{
targetNode->setItem(targetNode->getNext()->getItem());
targetNode->setNext(targetNode->getNext()->getNext());
//delete targetNode->getNext();
mSize--;
}
return this;
}
int size() const
{
return mSize;
}
bool isEmpty() const
{
return (mFirstNode == NULL) ? true : false;
}
protected:
ListNode<K>* getNodeAtPosition(int position)
{
ListNode<K>* current = NULL;
if (mFirstNode != NULL && position < mSize)
{
current = mFirstNode;
for (int i = 0; i < position; i++)
{
current = current->getNext();
}
}
return current;
}
private:
int mSize;
ListNode<K>* mFirstNode;
};
#endif /* LINKEDLIST_H_ */
Suggestions?
Part of your problem is here:
ListNode(T item)
{
mItem = item; // for a std::string, this will be a class member, non-pointer
mNext = NULL;
mPrev = NULL;
}
ListNode(T item, ListNode<T>* next, ListNode<T>* prev)
{
mItem = item; // same here
mNext = next;
mPrev = prev;
}
~ListNode()
{
delete &mItem; // you are attempting to delete an item you never created
}
You should either change your constructors to create a T* object on the heap (which will then be deleted in your destructor), or remove the delete line from your destructor.
This problem will be evident with far more than just std::string, by the way.
Somewhere in your program you are doing this:
std::string s(nullptr);
Calling std::string's constructor with a null pointer is causing it to throw a std::logic_error exception.
From the standard:
ยง 21.4.2
basic_string(const charT* s, size_type n, const Allocator& a = Allocator());
Requires: s shall not be a null pointer and n < npos.
It seems it's not possible to pass std::string as template argument...
Strings as Template Arguments
Now I use an "old" - char const* - to achieve the expected result, even if I have to implement my personal "utils" methods to work with those pointers now...