Beispiel #1
0
static void test_heap(const T* data, unsigned data_size, const T* sorted_data,
                      const T* to_remove, unsigned removed_size, const T* sorted_after_remove,
                      const T& not_in_heap) {
    BinaryHeap<T, Compare> heap;
    const size_t initial_capacity = data_size / 2, grow_capacity = (data_size * 3) / 2, alignment = 4;
    UAllocTraits_t traits = {0};
    TEST_ASSERT_TRUE(heap.init(initial_capacity, grow_capacity, traits, alignment));

    // Fill the heap with data
    for (unsigned i = 0; i < data_size; i++) {
        heap.insert(data[i]);
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_EQUAL(data_size, heap.get_num_elements());

    // Remove and check root at each step
    for (unsigned i = 0; i < data_size; i ++) {
        T root = heap.get_root();
        TEST_ASSERT_TRUE(root == sorted_data[i]);
        heap.remove_root();
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_TRUE(heap.is_empty());

    // Put everything back again
    for (unsigned i = 0; i < data_size; i++) {
        heap.insert(data[i]);
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_EQUAL(data_size, heap.get_num_elements());

    // And check removing
    for (unsigned i = 0; i < removed_size; i ++) {
        TEST_ASSERT_TRUE(heap.remove(to_remove[i]));
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_TRUE(!heap.remove(not_in_heap)); // this element is not in the heap
    TEST_ASSERT_EQUAL(data_size - removed_size, heap.get_num_elements());
    // Remove and check root at each step
    for (unsigned i = 0; i < data_size - removed_size; i ++) {
        T root = heap.pop_root();
        TEST_ASSERT_TRUE(root == sorted_after_remove[i]);
        TEST_ASSERT_TRUE(heap.is_consistent());
    }
    TEST_ASSERT_TRUE(heap.is_empty());
    TEST_ASSERT_EQUAL(0, heap.get_num_elements());
}