debugDDe (1158408), страница 2

Файл №1158408 debugDDe (Раздаточные материалы) 2 страницаdebugDDe (1158408) страница 22019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 2)

The following structure is defined for the table:

typedef struct tag_TABLE

{

byte

IsInit;

s_COLLECTION

cTable;

size_t

TableSize;

size_t

CurSize;

size_t

ElemSize;

PFN_TABLE_ELEMDESTRUCTOR

Destruct;

}

TABLE;

IsInit

flag of the table initialization. It is used for postponed initialization improve performance.

cTable

a set of pointers to allocated memory blocks

TableSize

number of elements to allocate when the table is expanded

CurSize

number of used elements in the current table block

ElemSize

size in bytes of one element

Destruct

pointer to the function with prototype

void (*PFN_TABLE_ELEMDESTRUCTOR)(void *Elem).

This function is called for each table element when it is removed from the table.

The following calls are intended for work with the table:

void table_Init(TABLE *tb, size_t TableSize, size_t ElemSize, PFN_TABLE_ELEMDESTRUCTOR Destruct)

tb

pointer to the TABLE structure to be initialized.

TableSize

number of the elements to allocate when expanding the table

ElemSize

size in bytes of one table element

Destuct

pointer to table element destructor function. It can be NULL.

Table initialization. This function should be called before using the table.

void table_Done( TABLE *tb )

tb

pointer to the TABLE structure.

Table destructor. This function should be called upon usage of the table to free allocated memory. It calls element destructor for each element of the table.

long table_Count( TABLE *tb )

tb

pointer to the TABLE structure.

The function returns number of used table elements.

void *table_At( TABLE *tb, long No )

tb

pointer to the TABLE structure.

No

zero based element number. The program will aborted if the No does not fall to number of elements range

The function returns the pointer to the specified table element.

long table_Put( TABLE *tb, void *Struct )

tb

pointer to the TABLE structure.

Struct

pointer to the inserted element. Only ElemSize bytes will be copied into the table

The function inserts a new element into the table.

void *table_GetNew( TABLE *tb )

tb

pointer to the TABLE structure.

The function inserts allocates a space for new element into the table and returns a pointer to this element. The function is more effective then table_Put() because no memory copy operation is performed.

void table_RemoveFrom( TABLE *tb, long Index )

tb

pointer to the TABLE structure.

Index

element number from which elements will be removed.

The function removes elements of the table starting from number Index. The element with the number Index itself remains in the table.

void table_RemoveAll( TABLE *tb )

tb

pointer to the TABLE structure.

The function removes all elements from the table and frees allocated memory.

void table_Iterator(TABLE *tb, PFN_TABLEITERATION Proc, void *Param1, void *Param2)

tb

pointer to the TABLE structure.

Proc

iteration function with the following prototype:

void (*PFN_TABLEITERATION)( void *Elem, void *Param1, void *Param2 ).

This function will be called for each element of the table

Param1

the parameter passed as Param1 into the Proc function

Param2

the parameter passed as Param2 into the Proc function

The function applies the same operation to each element of the table.

4.2Hash-table

The hash-table is intended to store elements of long type accessed by a key. The hash-table is organized as a table of fixed size. All elements with the same hash-value are put to a chain that is associated with the hash-value. When an element is searched, the hash-value is calculated using the key, and then each element of the corresponding chain is examined.

The hash-table consists of two parts: a hash-index and a hash-array keeping keys and associated values. The following steps are performed to find the specified value using a key. The hash-value is calculated using the key. The element of the hash-index determined by the hash-value is extracted. The element contains an element number in the hash-array. This hash-array element starts the chain of elements with the same hash-value. Each element of the hash-array has NextElem field that refers to the next chain element. The zero value of this field means the end of the chain. While elements are searched, the key field of the elements is compared with the specified key. If the keys are matched, the value of the Assign field is returned as result of the search.

The following algorithms can be used to calculate hash-values:

  • StandartHashCalc. The following function is used: HASH-VALUE = (long)Key % HashIndexSize, where Key is the element's key, HashIndexSize is the size of the hash-index, % is operator to take the reminder of integral division.

  • OffsetHashCalc. The following function is used: HASH-VALUE = ((long)Key >> Offset)% HashIndexSize, where Key is the element's key, HashIndexSize is the size of the hash-index, Offset is an offset specified as parameter, % is operator to take the reminder of integral division, and >> is shift right operator. If Offset = 0, this algorithm is identical to StandartHashCalc.

The following picture schematically shows realization of hash-table:

Figure 1. Foundation of hash-table

The following types are defined for the hash-table:

Hash-value:

typedef size_t HASH_VALUE

Key value:

typedef unsigned long STORE_VALUE

Structure of the hash-table element:

typedef struct tag_HashList

{

long

NextElem;

STORE_VALUE

Value;

long

Assign;

}

HashList;

NextElem

the number of the next chain element. It is equal to zero for the last chain element.

Value

the element key. This key is used to access to the element

Assign

the stored value

Structure of the hash-table:

typedef struct tag_HASH_TABLE

{

TABLE

hTable;

long *

pIndex;

size_t

IndexSize;

PFN_CALC_HASH_FUNC

HashFunc;

unsigned long *

pElements;

unsigned long

statCompare, statPut, statFind;

}

HASH_TABLE;

hTable

the hash-array of hash-table elements. The hash-array is organized as a table structure.

pIndex

the hash-index, an array containing starting indexes of the chains. The hash-value gives an index in the hash-index.

IndexSize

size of the pIndex array.

HashFunc

pointer to the function that calculates a hash-value by a key.

pElements

array that keeps chain sizes of corresponding pIndex elements. It is used to store statistics of using hash-table elements.

statCompare, statPut, statFind

statistics fields. These fields contain count of ‘compare’, ‘put’ and ‘find’ actions performed with the hash-table.

The following functions are intended for working with hash-table:

void hash_Init(HASH_TABLE *HT, size_t IndexSize, int TableSize, PFN_CALC_HASH_FUNC Func)

HT

pointer to HASH_TABLE structure to be initialized.

IndexSize

the size of the hash-index

TableSize

hash-array increment value for hash-array expansion.

Func

pointer to the function that calculates hash-value. If Func is, equal to NULL then the standard function StandartHashCalc will be applied. The function StandartHashCalc calculates hash-value using the following formula: <hash-value> = <key> % IndexSize.

The function performs all required initialization operations for hash-table.

void hash_Done( HASH_TABLE *HT )

HT

pointer to the HASH_TABLE structure.

The function uninitializes the hash-table. The function frees all allocated memory for hash-table elements.

long hash_Find( HASH_TABLE *HT, STORE_VALUE Val )

HT

pointer to the HASH_TABLE structure.

Val

the key of the element.

The function finds a value by the specified key.

void hash_Insert( HASH_TABLE *HT, STORE_VALUE Val, long Assign )

HT

pointer to the HASH_TABLE structure.

Val

the key of inserted element.

Assign

the value associated with the key.

The function inserts a new element into the hash-table.

void hash_Change( HASH_TABLE *HT, STORE_VALUE Val, long Assign )

HT

pointer to the HASH_TABLE structure.

Val

the key of changed element.

Assign

the value associated with the key.

The function updates an associated value for the specified key.

void hash_Remove( HASH_TABLE *HT, STORE_VALUE Val )

HT

pointer to the HASH_TABLE structure.

Val

the key of removed element.

the function removes an element with the specified key.

void hash_Iterator(HASH_TABLE *HT, PFN_HASHITERATION Proc, void *Param)

HT

pointer to the HASH_TABLE structure.

Proc

iteration function with the following prototype:

void (*PFN_HASHITERATION)(long Elem, void *Param)

where Elem is associated value of a hash-table element and Param is additional parameter. This function will be called for each hash-table element.

Param

parameter passed as Param into the Proc function

The function applies the same operation for all the hash-table elements.

void hash_RemoveAll( HASH_TABLE *HT )

HT

pointer to the HASH_TABLE structure.

The function removes all elements from the hash-table.

4.3Table of variables

The table of variables is intended to store information about variables and to fast access to it using the variable address.

Each element of a table of variables keeps the reference to the same variable at the previous level (if the variable is used at several levels), address of variable, class of using, and additional information that depends on class of using.

Характеристики

Список файлов учебной работы

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7021
Авторов
на СтудИзбе
260
Средний доход
с одного платного файла
Обучение Подробнее