Вставить функцию в таблицу Ha sh C ++ - PullRequest
0 голосов
/ 26 февраля 2020

Так что я работаю за тем же столом sh, что и раньше. Я пытался реализовать функцию вставки, но она ведет себя странно. Возьмите эту информацию и запишите ее в файл для DATAIN:

TATUNG CO.EL PR. LONG BEACH CA
KAMERMAN LCIRRUS BEAVERTON, OR
QUADRAM COLOACH AV NORCROSS GE
AST RESEARALTON AV IRVINE   CA
EXPRESS SYREMING SCHAUMBURG IL
DAC SW INCSPRING VAL DALLAS TX

Этот код разделен на одну заглушку.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdio.h>
#include <string.h> // for strcpy()

using namespace std;

typedef char STR10[10+1];
typedef char STR20[20+1];

struct SLOT
{
  STR10 key;
  STR20 data;
};

struct BUCKET
{
  SLOT entry[3];
  int count;
  int overflow;
};

struct HASHTABLE
{
  BUCKET pBkt[20];
  BUCKET oBkt[10];
  int nextFreeOBucket = 0;
};

void InitializeHT (HASHTABLE ht, int MAXPBUCKETS, int MAXOBUCKETS, int MAXSLOTS);
int HashFunction (STR10 key);
void InsertIntoHT (HASHTABLE ht, STR10 &key, STR20 &data);

int main()
{
    int maxP = 20;
    int maxO = 10;
    int maxS = 3;
    HASHTABLE ht;

    STR10 mKey;
    STR20 mData;
    STR10 sKey;

    InitializeHT (ht, maxP, maxO, maxS);

    FILE * inFile;
    inFile = fopen("DATAIN.dat","rb");
    if (inFile == NULL)
    {
        cout << " DATAIN file access error ... \n";
        cout << " Terminating application ... \n ";
        cout << " Press any key ... \n ";
        return -100;
    }
    char crLF;

    while (!feof(inFile))
    {
        fscanf(inFile,"%10c%20c\n",mKey,mData);
        mKey[10] = mData[20] = 0; // add string terminators
        printf(" MyKey: %10s\n MyData: %20s\n",mKey,mData);
        cin.ignore(80,'\n'), cin.get();
        InsertIntoHT (ht, mKey, mData);
    }

    fclose(inFile);

    return 0;
}

void InitializeHT (HASHTABLE ht, int MAXPBUCKETS, int MAXOBUCKETS, int MAXSLOTS)
{
    for (int i = 0; i < MAXPBUCKETS; i++)
    {
        ht.pBkt[i].count = 0;              // set count field to 0
        ht.pBkt[i].overflow = -1;          // set overflow field to -1
    }

    for (int i = 0; i < MAXOBUCKETS; i++)
    {
        ht.oBkt[i].count = 0;              // set count field to 0
        ht.oBkt[i].overflow = -1;          // set overflow field to -1
    }
    // each slot is empty, count and overflow have been initialized
}

int HashFunction (STR10 key)
{
    int iValue = int(key[1]) + int(key[3]) + int(key[5]);
    int hashIndex = iValue % 20;

    return hashIndex;
}

void InsertIntoHT(HASHTABLE ht, STR10 key, STR20 data)
{
    int hashIndex = HashFunction(key);
    int c = ht.pBkt[hashIndex].count;
    int c2 = ht.oBkt[hashIndex].count;
    int c3 = ht.oBkt[ht.nextFreeOBucket].count;

    if (c <= 2)
    {
      strcpy(ht.pBkt[hashIndex].entry[c].key,key);
      strcpy(ht.pBkt[hashIndex].entry[c].data,data);
      cout << ht.pBkt[hashIndex].entry[c].key << " / " << ht.pBkt[hashIndex].entry[c].data << endl;
    }

    else
    {
      if (ht.pBkt[hashIndex].overflow != -1)      // it has an overflow; check the overflow
      {
        hashIndex = ht.pBkt[hashIndex].overflow;  //using the overflow field to navigate through the buckets as hashIndex

        /*strcpy(ht.oBkt[hashIndex].entry[c2].key,key); // this causes the crash
        strcpy(ht.oBkt[hashIndex].entry[c2].data,data);
        c2++;

        cout << ht.oBkt[hashIndex].entry[c2].key << " / " << ht.oBkt[hashIndex].entry[c2].data << endl;*/
      }

      else       // it does not have an overflow
      {
        ht.pBkt[hashIndex].overflow = ht.nextFreeOBucket;
        int c3 = ht.oBkt[ht.nextFreeOBucket].count;

        strcpy(ht.oBkt[ht.nextFreeOBucket].entry[c3].key,key);
        strcpy(ht.oBkt[ht.nextFreeOBucket].entry[c3].data,data);
        c3++;                       // increment the overflow bucket's count
        ht.nextFreeOBucket++;       // allocate the next free overflow bucket
        cout << ht.oBkt[ht.nextFreeOBucket].entry[c3].key << " / " << ht.oBkt[ht.nextFreeOBucket].entry[c3].data << endl;
      }
    } // else/
}

Функция вставки отлично работает для определенных строк. Но если я вставлю НИЧЕГО в оператор else if после назначения переполнения в hashIndex, код вылетает. Я пробовал несколько способов, и ничего не работает.

1 Ответ

0 голосов
/ 26 февраля 2020
strcpy(ht.oBkt[hashIndex].entry[c2].key,key); // this causes the crash

Конечно, это вызывает cra sh, потому что у вас есть только 10 элементов в массиве oBkt, но доступ к нему осуществляется с помощью hashIndex, который может иметь значения от 0 до 19.

Как Кроме того, обратите внимание, почему вы используете C конструкции: строки, доступ к файлу и т. д. c. Если вы пытаетесь писать на C ++?

Если вы использовали std::array вместо нативных массивов, вы даже, вероятно, получите осмысленное сообщение об исключении того, почему произошло cra sh ...

...