Zawsze gdy miałem w programie zbiór dostępnych słów był to wektor stringów. Przy paru wyrazach nie ma problemu ale przy paru tysiącach już jest... Spróbowałem to zrobić bez wektora i wyszło mi takie coś:
types.h
#ifndef TYPES_H
#define TYPES_H
#include<cstdlib>
#include<iostream>
struct Alphabet
{
char letters[2][26];
Alphabet();
Alphabet(const Alphabet & target);
~Alphabet();
};
class StringMap
{
StringMap**cells;
unsigned int number;
public:
void add(std::string source,Alphabet alph);
bool contains(std::string source,Alphabet alph);
StringMap();
StringMap(const StringMap & target);
~StringMap();
};
#endif // TYPES_H
types.cpp
#include "types.h"
Alphabet::Alphabet()
{
for (unsigned short i=0; i<26; i++)
{
letters[0][i]='a'+i;
letters[1][i]='a'+i;
}
}
Alphabet::Alphabet(const Alphabet & target)
{
for (unsigned short i=0; i<26; i++)
{
letters[0][i]=target.letters[0][i];
letters[1][i]=target.letters[1][i];
}
}
Alphabet::~Alphabet(){}
void StringMap::add(std::string source,Alphabet alph)
{
if (!contains(source,alph))
{
StringMap*next=this;
int num=0;
for (unsigned int i=0; i<source.size(); i++)
{
num=-1;
for (unsigned short j=0; j<26; j++)
{
if (alph.letters[0][j]==source[i])
{
num=j;
break;
}
else if (alph.letters[1][j]==source[i])
{
num=26+j;
break;
}
}
if (num==-1)
break;
if (next->cells[num]!=NULL)
{
next->cells[num]->number++;
}
else
next->cells[num]=new StringMap;
next=next->cells[num];
}
}
}
bool StringMap::contains(std::string source,Alphabet alph)
{
int num=0;
unsigned int pos=0;
StringMap * next=this;
for (unsigned int i=0; i<source.size(); i++)
{
num=-1;
for (unsigned int j=0; j<26; j++)
{
if (alph.letters[0][j]==source[i])
{
num=j;
break;
}
else if (alph.letters[1][j]==source[i])
{
num=j+26;
break;
}
}
if (num==-1)
break;
if (next->cells[num]==NULL)
{
return false;
}
next=next->cells[num];
pos=next->number;
}
for (unsigned int i=0; i<52; i++)
if (next->cells[i]!=NULL and next->cells[i]->number==pos)
return false;
return true;
}
StringMap::StringMap()
{
cells=new StringMap*[52];
for (unsigned int i=0; i<52; i++)
cells[i]=NULL;
number=0;
}
StringMap::StringMap(const StringMap & target)
{
cells=new StringMap*[52];
for (unsigned int i=0; i<52; i++)
{
if (target.cells[i]!=NULL)
{
cells[i]=new StringMap(*target.cells[i]);
}
else
cells[i]=NULL;
}
}
StringMap::~StringMap()
{
for (unsigned short i=0; i<52; i++)
if (cells[i]!=NULL)
delete cells[i];
delete[] cells;
}
niestety pojawiają się losowe błędy, na przykład mówi że nie ma jakiegoś słowa gdy wiele słów nachodzi na nie(w całości) albo mówi, że jakieś jest, mimo że nie zostało dodane. Nie wiem gdzie jest błąd, kod piszę od nowa 3 raz z tym samym efektem.