Reputation: 25
So, i'm trying to initialize a LinkedList class using an initializer_list.
template<typename T>
SortedList<T>::SortedList(initializer_list<T> e){
head_= new Node<T>(*e.begin());
long intcheck = 0;
T old;
for (auto x : e){
if(intcheck > 0){
Node<T>* curr = new Node<T>(old);
if(head_ == curr){
head_->next_ = new Node<T>(x);
}
curr->next_ = new Node<T>(x);
}
old = x;
intcheck = 1;
}
}
I get a seg fault when trying to print head_->next_ (nothing wrong with my print function)
Upvotes: 0
Views: 1221
Reputation: 7100
I'm assuming that you actually want the SortedList
to be sorted. If so, this will accomplish that goal. It bails out early if the initializer_list
is empty, but still leaves the object in a rational state.
template<typename T>
SortedList<T>::SortedList(initializer_list<T> e) : head_{nullptr} {
if (e.size() == 0)
return;
auto it = e.begin();
for (head_ = new Node<T>(*it); it != e.end(); ++it) {
Node<T> *n = new Node<T>(*it);
Node<T> *curr;
for (curr = head_; curr->next_ && curr->next_->data_ < *it; curr = curr->next_)
continue;
if (*it < curr->data_) {
n->next_ = curr;
head_ = n;
} else {
n->next_ = curr->next_;
curr->next_ = n;
}
}
}
For completeness, here's the destructor I used to test:
template<typename T>
SortedList<T>::~SortedList() {
while (head_->next_) {
Node<T> *t = head_->next_;
head_->next_ = t->next_;
delete t;
}
delete head_;
}
Upvotes: 1
Reputation: 2234
Your code says that head_->next_ will always be it's default value (we can't see the Node constructor so I can't say what that is).
for (auto x : e){
if(intcheck > 0){
Node<T>* curr = new Node<T>(old);
if(head_ == curr){
head_->next_ = new Node<T>(x);
}
It's OK do send your initializer list into the for loop this way. If it's empty you will just exit the loop immediately.
However your curr
pointer is allocated right there, while your head_
pointer was allocated above. They will therefore never be equal because you are comparing two pointers that you are allocating in the same function.
Upvotes: 0