Oleh
Oleh

Reputation: 9

no match for operator!=

I am trying to create linked list class and define the iterators, I have all of them except the last one. I dont get how to fix, i get this error when i compile my code:

no match for ‘operator!=’ in ‘recList.SortedList::begin with T = Record != recList.SortedList::end with T = Record’ a1q1main.cpp:114:37: note: candidates are: sortedlist.h:112:11: note: SortedList::iterator SortedList::iterator::operator!=(bool) [with T = Record, SortedList::iterator = SortedList::iterator] sortedlist.h:112:11: note: no known conversion for argument 1 from ‘SortedList::iterator’ to ‘bool’

It keeps on displaying this error no matter what i do I have declared operator == and everything is fine but the != complains Here is the code :

 class SortedList {
 struct Node {
    T data_;
    Node* next_;
    Node* prev_;
    Node(const T& data = T{}, Node* next = nullptr, Node* prev = nullptr) {
        data_ = data;
        next_ = next;
        prev_ = prev;
    }
};
Node* head_;
Node* tail_;
    public:
class const_iterator {
protected:
    Node* curr_;
public:
    const_iterator(Node* p) {
        curr_ = p;
    }
 .........
    const_iterator operator--(int) {
        const_iterator tmp = *this;
        curr_ = curr_->prev_;
        return tmp;
    }
    const T& operator*() const {
        return curr_->data_;
    }


     const_iterator operator==(bool){
            return false;
     }

    const_iterator operator!=(bool){
            return true;
    }

return;`

I need to fulfill the criteria below: operator != returns true if two iterators point at different nodes, false otherwise O(1)

I did not complete the logic of the operator, i just need to declare it properly so i dont get the error

Upvotes: 0

Views: 1441

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21609

The signature of your operator overloads are incorrect. You have them accepting a bool and returning an iterator. It should be the other way around.

Consider the operation you are performing

if(it1 == it2){
    // do stuff
}

You even return a bool in your functions despite the signature requiring a iterator as return value.

Instead implement the operator overloads in the required signature

bool operator==(sorted_list_iterator it){
    return (curr_->data_ == it.curr_->data_);
}

bool operator!=(sorted_list_iterator it){
    return !(*this == it);
}

Note you can use your operator== overload in your operator!= to avoid repeating the equality logic in two functions. You may also be required to allow for a null curr_ in those functions.

Upvotes: 1

Related Questions