专业程序代写(QQ:928900200)
Implement a HashSet class for elements of type string.
It has the
following functions:
bool add(const string &)
bool
contains(const string &) const
int size() const
In this exercise, you
need to implement some of the above functions, as well as several internal
functoins:
int find(const string & e) const
void resize(int
capacity2)
bool contains(const string & e) const
Hint:
The function
find(e) finds the first position starting from p=h%N, which is either empty or
equal to e. That is, find(e) should look like the following:
int
find(const string & e) const {
int p = hashIndex(e);
while (true)
{
if (…) return p;
p = (p + 1) % capacity;
}
}
EXAMPLE
INPUT
apple
orange
banana
apple
orange
apple
watermelonEXAMPLE
OUTPUT
3
true
false
主程序
#include <iostream>
#include
<string>
using namespace
std;
//////////////////////////
//
Interfaces
//
template <typename E>
class
Set
{
public:
virtual bool add(const E &) =
0;
virtual bool contains(const E &) const = 0;
virtual int
size() const = 0;
};
template <typename
E>
class HashFunction
{
public:
virtual
int getHashCode(const E & e) const =
0;
};
/////////////////////////
//
hash-function
//
class StringHashFunction : public
HashFunction<string>
{
public:
int
getHashCode(const string & text) const {
int code = 0;
for
(int i = 0; i < text.size(); ++ i) {
int code1 =
text[i];
code1 = code1 ? (i * 8 % 24);
code = code ^
code1;
}
return
code;
}
};
/////////////////////////
//
your class
//
class HashSet : public
Set<string>
{
private:
const
StringHashFunction hashFunction;
class
Entry
{
public:
string element;
bool
isInUse;
Entry() {
isInUse =
false;
}
};
Entry * entries;
int
capacity;
int count;
void initialize(int capacity2)
{
count = 0;
capacity = capacity2;
entries = new
Entry[capacity];
}
void assign(const HashSet & set2)
{
count = set2.count;
capacity =
set2.capacity;
entries = new Entry[capacity];
for (int i = 0;
i < capacity; ++ i) {
entries[i] =
set2.entries[i];
}
}
public:
HashSet()
{
initialize(2);
}
~HashSet() {
delete
[] entries;
}
HashSet(const HashSet & set2)
{
assign(set2);
}
HashSet & operator = (const
HashSet & set2) {
delete []
entries;
assign(set2);
return
(*this);
}
private:
int hashIndex(const
string & e) const {
int hashCode =
hashFunction.getHashCode(e);
return hashCode %
capacity;
}
int find(const string & e)
const;
void resize(int
capacity2);
public:
bool add(const string & e)
{
int index = find(e);
if (entries[index].isInUse)
{
return false;
}
entries[index].element =
e;
entries[index].isInUse = true;
++ count;
if (count
> capacity / 2) {
resize(capacity * 2);
}
return
true;
}
bool contains(const string & e)
const;
int size() const {
return
count;
}
};
#include
“source”
int main() {
HashSet set;
for (int i =
0; i < 5; ++ i) {
string text;
cin ?
text;
set.add(text);
}
cout ? set.size()
? endl;
for (int i = 0; i < 2; ++ i) {
string
text;
cin ? text;
if (set.contains(text)) {
cout
? “true” ? endl;
}
else {
cout
? “false”
? endl;
}
}
}