Перегрузка < < оператор с ++

Android не позволяет повторно использовать повторно используемый Bitmap. Просто комментируйте bitmap.recycle(), чтобы устранить эту ошибку. Подробнее нажмите здесь

-2
задан KP1O8 20 February 2019 в 23:34
поделиться

1 ответ

Определение operator<< может быть следующим:

std::ostream& operator<<(std::ostream& out, const LLSortedPosInt& l) {
    out << "<";
    NodePtr current = l.head;
    // check that it actually points to a Node before accessing any fields
    if(current) {
        out << current->key;
        // loop through the links and stream the keys
        while((current = current->next) != nullptr)
            out << "," << current->key;
    }
    out << ">";
    return out;
}

Конструктор LLSortedPosInt(int key) не должен создавать узел HEAD_OF_LIST, поскольку он ни для чего не используется. Таким образом, вы можете изменить этот конструктор, чтобы использовать тот, который у вас уже есть, для списка ключей через делегирование. Делегирование также облегчает добавление конструктора, используя initializer_list:

LLSortedPosInt(const int *keys=nullptr, size_t n=0) :
    head(nullptr)
{
    if(keys && n) {
        while(n--) {
            createNode(*keys);
            ++keys;
        }
    }
}

// single key construction
LLSortedPosInt(int key) :
    LLSortedPosInt(&key, 1) // delegate
{}

// construction using an initializer list
LLSortedPosInt(std::initializer_list<int> il) :
    LLSortedPosInt(il.begin(), il.size()) // delegate
{}

Интерфейс static createNode немного странный. Пользователям функции не нужно указывать указатель на следующий узел. Вот для чего предназначен контейнерный класс. Его можно превратить в обычную функцию-член и напрямую создать узел в правильном месте:

NodePtr createNode(int key) {
    NodePtr current = head;
    NodePtr previous = nullptr;

    while(current && (current->key < key)) {
        previous = current;
        current = current->next;
    }

    if(previous) {
        // insert the node between previous and previous->next
        NodePtr rv = new Node(key, previous->next);
        return previous->next = rv;
    } else {
        // insert the node first in the list
        NodePtr rv = new Node(key, head);
        return head = rv;
    }
}

Учитывая, что фактический Node выглядит примерно так:

struct Node {
    Node* next;
    int key;
    Node(int k, Node* n) : next(n), key(k) {}
    Node(const Node&) = delete;
    Node(Node&&) = delete;
    Node& operator=(const Node&) = delete;
    Node& operator=(Node&&) = delete;
    ~Node() = default;
};

using NodePtr = Node*;
0
ответ дан Ted Lyngmo 20 February 2019 в 23:34
поделиться
Другие вопросы по тегам:

Похожие вопросы: