我已经解决了我的问题,并且一切似乎都正常进行,除了我的输出中有一个随机行跳过而我也不知道为什么!真令人沮丧。如果有人看到我可能明显的不准确之处并指出来,那就太好了...
很抱歉,我把它全部都放在一个文件中,以使工作更轻松。.谢谢,如此,如此,如此之多。
我也有输出和输入数据的屏幕截图:
输入文件: stateData.txt
阿拉巴马州
蒙哥马利
阿拉斯加
朱诺
亚利桑那州
凤凰
阿肯色州
小石城
加利福尼亚
萨克拉曼多
科罗拉多州
丹佛
康涅狄格州
哈特福德
特拉华州
多佛
佛罗里达
塔拉哈西
佐治亚州
亚特兰大
夏威夷
火奴鲁鲁
爱达荷州
博伊西
伊利诺伊州
斯普林菲尔德
印第安纳州
印第安纳波利斯
爱荷华州
得梅因
#include <iostream>
#include <cassert>
#include <fstream>
#include <string>
#include <iomanip>
#include <cassert>
using namespace std;
//arrayListType.h
template <class elemType>
class arrayListType
{
public:
const arrayListType<elemType>& operator=
(const arrayListType<elemType>&);
//Overloads the assignment operator
bool isEmpty() const;
//Function to determine whether the list is empty
//Postcondition: Returns true if the list is empty;
// otherwise, returns false.
bool isFull() const;
//Function to determine whether the list is full.
//Postcondition: Returns true if the list is full;
// otherwise, returns false.
int listSize() const;
//Function to determine the number of elements in the list
//Postcondition: Returns the value of length.
int maxListSize() const;
//Function to determine the size of the list.
//Postcondition: Returns the value of maxSize.
void print() const;
//Function to output the elements of the list
//Postcondition: Elements of the list are output on the
// standard output device.
bool isItemAtEqual(int location, const elemType& item) const;
//Function to determine whether the item is the same
//as the item in the list at the position specified by
//Postcondition: Returns true if list[location]
// is the same as the item; otherwise,
// returns false.
void insertAt(int location, const elemType& insertItem);
//Function to insert an item in the list at the
//position specified by location. The item to be inserted
//is passed as a parameter to the function.
//Postcondition: Starting at location, the elements of the
// list are shifted down, list[location] = insertItem;,
// and length++;. If the list is full or location is
// out of range, an appropriate message is displayed.
void insertEnd(const elemType& insertItem);
//Function to insert an item at the end of the list.
//The parameter insertItem specifies the item to be inserted.
//Postcondition: list[length] = insertItem; and length++;
// If the list is full, an appropriate message is
// displayed.
void removeAt(int location);
//Function to remove the item from the list at the
//position specified by location
//Postcondition: The list element at list[location] is removed
// and length is decremented by 1. If location is out of
// range, an appropriate message is displayed.
void retrieveAt(int location, elemType& retItem) const;
//Function to retrieve the element from the list at the
//position specified by location.
//Postcondition: retItem = list[location]
// If location is out of range, an appropriate message is
// displayed.
void replaceAt(int location, const elemType& repItem);
//Function to replace the elements in the list at the
//position specified by location. The item to be replaced
//is specified by the parameter repItem.
//Postcondition: list[location] = repItem
// If location is out of range, an appropriate message is
// displayed.
void clearList();
//Function to remove all the elements from the list.
//After this operation, the size of the list is zero.
//Postcondition: length = 0;
int seqSearch(const elemType& item) const;
//Function to search the list for a given item.
//Postcondition: If the item is found, returns the location
// in the array where the item is found; otherwise,
// returns -1.
void insert(const elemType& insertItem);
//Function to insert the item specified by the parameter
//insertItem at the end of the list. However, first the
//list is searched to see whether the item to be inserted
//is already in the list.
//Postcondition: list[length] = insertItem and length++
// If the item is already in the list or the list
// is full, an appropriate message is displayed.
void remove(const elemType& removeItem);
//Function to remove an item from the list. The parameter
//removeItem specifies the item to be removed.
//Postcondition: If removeItem is found in the list,
// it is removed from the list and length is
// decremented by one.
arrayListType(int size = 100);
//constructor
//Creates an array of the size specified by the
//parameter size. The default array size is 100.
//Postcondition: The list points to the array, length = 0,
// and maxSize = size
arrayListType(const arrayListType<elemType>& otherList);
//copy constructor
~arrayListType();
//destructor
//Deallocates the memory occupied by the array.
protected:
elemType *list; //array to hold the list elements
int length; //to store the length of the list
int maxSize; //to store the maximum size of the list
};
/*******************************************************************
********************************************************
arrayListTypeADT function definitions
********************************************************
*******************************************************************/
template <class elemType>
bool arrayListType<elemType>::isEmpty() const
{
return (length == 0);
}
template <class elemType>
bool arrayListType<elemType>::isFull() const
{
return (length == maxSize);
}
template <class elemType>
int arrayListType<elemType>::listSize() const
{
return length;
}
template <class elemType>
int arrayListType<elemType>::maxListSize() const
{
return maxSize;
}
template <class elemType>
void arrayListType<elemType>::print() const
{
for (int i = 0; i < length; i++)
cout << list[i] << " ";
cout << endl;
}
template <class elemType>
bool arrayListType<elemType>::isItemAtEqual
(int location, const elemType& item) const
{
return(list[location] == item);
}
template <class elemType>
void arrayListType<elemType>::insertAt
(int location, const elemType& insertItem)
{
if (location < 0 || location >= maxSize)
cerr << "The position of the item to be inserted "
<< "is out of range" << endl;
else
if (length >= maxSize) //list is full
cerr << "Cannot insert in a full list" << endl;
else
{
for (int i = length; i > location; i--)
list[i] = list[i - 1]; //move the elements down
list[location] = insertItem; //insert the item at the
//specified position
length++; //increment the length
}
} //end insertAt
template <class elemType>
void arrayListType<elemType>::insertEnd(const elemType& insertItem)
{
if (length >= maxSize) //the list is full
cerr << "Cannot insert in a full list" << endl;
else
{
list[length] = insertItem; //insert the item at the end
length++; //increment the length
}
} //end insertEnd
template <class elemType>
void arrayListType<elemType>::removeAt(int location)
{
if (location < 0 || location >= length)
cerr << "The location of the item to be removed "
<< "is out of range" << endl;
else
{
for (int i = location; i < length - 1; i++)
list[i] = list[i + 1];
length--;
}
} //end removeAt
template <class elemType>
void arrayListType<elemType>::retrieveAt
(int location, elemType& retItem) const
{
if (location < 0 || location >= length)
cerr << "The location of the item to be retrieved is "
<< "out of range." << endl;
else
retItem = list[location];
} //end retrieveAt
template <class elemType>
void arrayListType<elemType>::replaceAt
(int location, const elemType& repItem)
{
if (location < 0 || location >= length)
cerr << "The location of the item to be replaced is "
<< "out of range." << endl;
else
list[location] = repItem;
} //end replaceAt
template <class elemType>
void arrayListType<elemType>::clearList()
{
length = 0;
} //end clearList
template <class elemType>
arrayListType<elemType>::arrayListType(int size)
{
if (size < 0)
{
cerr << "The array size must be positive. Creating "
<< "an array of size 100. " << endl;
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new elemType[maxSize];
assert(list != NULL);
}
template <class elemType>
arrayListType<elemType>::~arrayListType()
{
delete[] list;
}
template <class elemType>
arrayListType<elemType>::arrayListType
(const arrayListType<elemType>& otherList)
{
maxSize = otherList.maxSize;
length = otherList.length;
list = new elemType[maxSize]; //create the array
assert(list != NULL); //terminate if unable to allocate
//memory space
for (int j = 0; j < length; j++) //copy otherList
list[j] = otherList.list[j];
} //end copy constructor
template <class elemType>
const arrayListType<elemType>& arrayListType<elemType>::operator=
(const arrayListType<elemType>& otherList)
{
if (this != &otherList) //avoid self-assignment
{
delete[] list;
maxSize = otherList.maxSize;
length = otherList.length;
list = new elemType[maxSize]; //create the array
assert(list != NULL); //if unable to allocate memory
//space, terminate the program
for (int i = 0; i < length; i++)
list[i] = otherList.list[i];
}
return *this;
}
template <class elemType>
int arrayListType<elemType>::seqSearch(const elemType& item) const
{
int loc;
bool found = false;
// keeping track of the number of search comparisons
int count = 0;
for (loc = 0; loc < length; loc++)
count++;
if (list[loc] == item)
{
found = true;
break;
}
cout << "Sequential search comparisons" << count << endl;
if (found)
return loc;
else
return -1;
} //end seqSearch
template <class elemType>
void arrayListType<elemType>::insert(const elemType& insertItem)
{
int loc;
if (length == 0) //list is empty
list[length++] = insertItem; //insert the item and
//increment the length
else if (length == maxSize)
cerr << "Cannot insert in a full list." << endl;
else
{
loc = seqSearch(insertItem);
if (loc == -1) //the item to be inserted
//does not exist in the list
list[length++] = insertItem;
else
cerr << "the item to be inserted is already in "
<< "the list. No duplicates are allowed." << endl;
}
} //end insert
template<class elemType>
void arrayListType<elemType>::remove(const elemType& removeItem)
{
int loc;
if (length == 0)
cerr << "Cannot delete from an empty list." << endl;
else
{
loc = seqSearch(removeItem);
if (loc != -1)
removeAt(loc);
else
cout << "The item to be deleted is not in the list."
<< endl;
}
} //end remove
// hashT.h
template <class elemType>
class hashT
{
public:
void insert(int hashIndex, const elemType& rec);
//Function to insert an item in the hash table. The first
//parameter specifies the initial hash index of the item to
//be inserted. The item to be inserted is specified by the
//parameter rec.
//Postcondition: If an empty position is found in the hash
// table, rec is inserted and the length is incremented by
// one; otherwise, an appropriate error message is
// displayed.
void search(int& hashIndex, const elemType& rec, bool& found) const;
//Function to determine whether the item specified by the
//parameter rec is in the hash table. The parameter hashIndex
//specifies the initial hash index of rec.
//Postcondition: If rec is found, found is set to true and
// hashIndex specifies the position where rec is found;
// otherwise, found is set to false.
bool isItemAtEqual(int hashIndex, const elemType& rec) const;
//Function to determine whether the item specified by the
//parameter rec is the same as the item in the hash table
//at position hashIndex.
//Postcondition: Returns true if HTable[hashIndex] == rec;
// otherwise, returns false.
void retrieve(int hashIndex, elemType& rec) const;
//Function to retrieve the item at position hashIndex.
//Postcondition: If the table has an item at position
// hashIndex, it is copied into rec.
void remove(int hashIndex, const elemType& rec);
//Function to remove an item from the hash table.
//Postcondition: Given the initial hashIndex, if rec is found
// in the table it is removed; otherwise, an appropriate
// error message is displayed.
void print() const;
//Function to output the data.
hashT(int size = 101);
//constructor
//Postcondition: Create the arrays HTTable and indexStatusList;
// initialize the array indexStatusList to 0; length = 0;
// HTSize = size; and the default array size is 101.
~hashT();
//destructor
//Postcondition: Array HTable and indexStatusList are deleted.
// added for problem from book
int hashFunc(string name);
// PostCondition: hash funtion to determine the hash address of an item, uses
// the name of the state as the key to determine the hash address. Assume
// the state's name is a string of no more than 15 characters.
// returns the address.
private:
elemType *HTable; //pointer to the hash table
int *indexStatusList; //pointer to the array indicating the
//status of a position in the hash table
int length; //number of items in the hash table
int HTSize; //maximum size of the hash table
};
/*******************************************************************
hashT.h function definitions for PROBLEM 7 start here:
Write the definitions of the functions search, isItemAtEqual, retrieve,
remove, and print, the constructor, and the destructor for the class
hashT, as described in the section, "Hashing: Implementation Using Quadratic
Probing," of this chapter. Also, write a program to test various hashing
operations.
*******************************************************************/
template <class elemType>
void hashT<elemType>::insert(int hashIndex, const elemType& rec)
{
int pCount;
int inc;
pCount = 0;
inc = 1;
while (indexStatusList[hashIndex] == 1 && HTable[hashIndex] != rec && pCount < HTSize / 2)
{
pCount++;
hashIndex = (hashIndex + inc) % HTSize;
inc = inc + 2;
}
if (indexStatusList[hashIndex] != 1)
{
HTable[hashIndex] = rec;
indexStatusList[hashIndex] = 1;
length++;
}
else
if (HTable[hashIndex] == rec)
cerr << "Error: No duplicates are allowed." << endl;
else
cerr << "Error: The table is full. "
<< "Unable to resolve the collision." << endl;
}
template <class elemType>
void hashT<elemType>::search(int& hashIndex, const elemType& rec, bool& found) const
{
int pCount;
int inc;
pCount = 0;
inc = 1;
while (indexStatusList[hashIndex] != 0 && HTable[hashIndex] != rec && pCount < HTSize / 2)
{
pCount++;
hashIndex = (hashIndex + inc) % HTSize;
inc = inc + 2;
}
if (HTable[hashIndex] == rec && indexStatusList[hashIndex] == 1)
{
found == true;
}
else
{
found == false;
}
}
template <class elemType>
bool hashT<elemType>::isItemAtEqual(int hashIndex, const elemType& rec) const
{
if (indexStatusList[hashIndex] != 1)
{
return false;
}
else
{
return HTable[hashIndex] == rec;
}
}
template <class elemType>
void hashT<elemType>::retrieve(int hashIndex, elemType& rec) const
{
if (indexStatusList[hashIndex] == 1)
{
rec = HTable[hashIndex];
}
else
{
cout << "Cannot find the item at the hash index." << endl;
}
}
template <class elemType>
void hashT<elemType>::remove(int hashIndex, const elemType& rec)
{
bool found;
search(hashIndex, rec, found);
if (found)
{
indexStatusList[hashIndex] = -1;
length--;
}
else
{
cout << "Cannot find the item in the hash table to remove." << endl;
}
}
//Function to output the data.
//print
template <class elemType>
void hashT<elemType>::print() const
{
for (int i = 0; i < HTSize; i++)
{
if (indexStatusList[i] == 1)
{
cout << HTable[i] << endl;
}
}
}
template <class elemType>
hashT<elemType>::hashT(int size)
{
HTable = new elemType[size];
indexStatusList = new int[size];
HTSize = size;
length = 0;
for (int i = 0; i < size; i++)
{
indexStatusList[i] = 0;
}
}
template <class elemType>
hashT<elemType>::~hashT()
{
delete[] HTable;
delete[] indexStatusList;
}
template <class elemType>
int hashT<elemType>::hashFunc(string name)
{
int i;
int sum;
int len;
i = 0;
sum = 0;
len = name.length();
for (int k = 0; k < 15 - len; k++)
name = name + ' '; //increase the length of name to 15 characters
for (int k = 0; k < 5; k++)
{
sum = sum + static_cast<int>(name[i]) * 128 * 128
+ static_cast<int>(name[i + 1]) * 128
+ static_cast<int>(name[i + 2]);
i = i + 3;
}
// address
return sum % HTSize;
}
// stateData.h
class stateData
{
public:
// constructor to initialize state name and capital
// line 1 is name, line 2 is capital
stateData(string name = " ", string capital = " ")
{
stateName = name;
stateCapital = capital;
}
// function to manipulate retrieving the state's name
string getStateName()
{
return stateName;
}
// function to manipulate setting the state's name
void setStateName(string n)
{
stateName = n;
}
// function to manipulate retrieving the state's capital
string getStateCapital()
{
return stateCapital;
}
// function to manipulate setting the state's capital
void setStateCapital(string c)
{
stateCapital = c;
}
// overloading the input stream operator to compare two states by their name
// friend is used to access private members
friend istream &operator >> (istream &in, stateData& stateName)
{
getline(in, stateName.stateName);
getline(in, stateName.stateCapital);
return in;
}
// overloading the output stream operator to compare two states by their name
// friend is used to access private members
friend ostream &operator<<(ostream &out, stateData& stateName)
{
out << stateName.getStateName() << ", ";
out << stateName.getStateCapital();
return out;
}
// overloading the assignment operator to compare two states by their name
stateData &operator=(const stateData &other)
{
stateName = other.stateName;
stateCapital = other.stateCapital;
return *this;
}
// overloading boolean operator to compare two states by their name
// check to see the state names are the same
bool operator==(const stateData &other) const
{
return stateName == other.stateName;
}
// check to see the state names are not the same
bool operator!=(const stateData &other) const
{
return stateName != other.stateName;
}
// check to see if the original state is smaller than or equal to compared state
bool operator<=(const stateData &other) const
{
return stateName <= other.stateName;
}
// check to see if the original state is smaller than compared state
bool operator<(const stateData &other) const
{
return stateName < other.stateName;
}
// check to see if the original state is larger than or equal to compared state
bool operator>=(const stateData &other) const {
return stateName >= other.stateName;
}
// check to see if the original state is larger than compared state
bool operator>(const stateData &other) const
{
return stateName > other.stateName;
}
private:
string stateName;
string stateCapital;
};
// orderedArrayListType.h
template<class elemType>
class orderedArrayListType : public arrayListType<elemType>
{
public:
void insertOrd(const elemType&);
void fill();
int binarySearch(const elemType& item) const;
int binaryWithSeqSearch(const elemType& item)const;
orderedArrayListType(int size = 100);
};
template <class elemType>
void orderedArrayListType<elemType>::insertOrd(const elemType& item)
{
int first = 0;
int last = length - 1;
int mid;
bool found = false;
if (length == 0) //the list is empty
{
list[0] = item;
length++;
}
else if (length == maxSize)
cerr << "Cannot insert into a full list." << endl;
else
{
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == item)
found = true;
else if (list[mid] > item)
last = mid - 1;
else
first = mid + 1;
}//end while
if (found)
cerr << "The insert item is already in the list. "
<< "Duplicates are not allowed." << endl;
else
{
if (list[mid] < item)
mid++;
insertAt(mid, item);
}
}
}//end insertOrd
template<class elemType>
int orderedArrayListType<elemType>::binaryWithSeqSearch
(const elemType& item) const
{
int first = 0;
int last = length - 1;
int mid;
bool found = false;
int count = 0;
while (first <= last && !found)
{
mid = (first + last) / 2;
count++;
if (list[mid] == item)
found = true;
else if (list[mid] > item)
last = mid - 1;
else
first = mid + 1;
//once the partition has reached 15 or below
if (last - first <= 15) {
for (int i = first; i <= last; i++) {
count++;
if (list[i] == item) {
found = true;
break;
}
}
break;
}
}
cout << "Binary search with sequential comparisons: " << count << endl;
if (found)
return mid;
else
return -1;
}//end binaryWithSeqSearch
template<class elemType>
int orderedArrayListType<elemType>::binarySearch
(const elemType& item) const
{
int first = 0;
int last = length - 1;
int mid;
bool found = false;
int count = 0;
count = 2;
while (first <= last && !found)
{
mid = (first + last) / 2;
count++;
if (list[mid] == item)
found = true;
else if (list[mid] > item)
last = mid - 1;
else
first = mid + 1;
}
cout << "Binary search comparisons: " << count << endl;
if (found)
return mid;
else
return -1;
}//end binarySearch
template<class elemType>
orderedArrayListType<elemType>::orderedArrayListType(int size)
: arrayListType<elemType>(size)
{
}
template<class elemType>
void orderedArrayListType<elemType> ::fill()
{
int seed = 47;
int multiplier = 2743;
int addOn = 5923;
while (listSize() < maxListSize())
{
insertOrd(seed);
seed = int((seed * multiplier + addOn) % 100000);
}
}
// main.cpp
void main()
{
cout << "\n********************************************************************************\n" << endl;
// create stateHashTable with default size 101
hashT<stateData> stateHashTable(101);
// open file with just state name and state capital as specified
ifstream infile;
infile.open("stateData.txt");
// use the information from the file to make the hash table
while (infile)
{
// run the file through stateData to keep track of its information
stateData listedState;
infile >> listedState;
// initializing the index using the hash function to determine the hash address of an item
// using the name of the state as the key to determine the hash address
int stateIndex = stateHashTable.hashFunc(listedState.getStateName());
// insert/add the state to the hash table using quadratic probing
stateHashTable.insert(stateIndex, listedState);
}
// close file so the operating system is notified resources are available
infile.close();
// initializing values to be run through functions
bool foundFirst;
int hashIndex;
string stateName;
stateData searchState;
cout << "Enter the name of a state: ";
cin >> stateName;
// setting hashIndex to the index result of running the input state through the hashFunc function
hashIndex = stateHashTable.hashFunc(stateName);
// setting searchState to the result of running the
// input state through stateData to keep track of information
searchState = stateData(stateName);
// search to see if user input state is in the hash table,
// then set foundFirst to true
stateHashTable.search(hashIndex, searchState, foundFirst);
// Function to determine whether the user input state is in the hash table at position hashIndex
if (foundFirst && stateHashTable.isItemAtEqual(hashIndex, searchState))
{
cout << "\nThe state and associated capital: " << endl;
stateHashTable.retrieve(hashIndex, searchState);
// print the user input state as well as the associated capital
cout << searchState << endl;
}
// remove the user input from the hash table
stateHashTable.remove(hashIndex, searchState);
// initializing the value to compare foundFirst to
bool foundSecond;
// search the hash table for the state and set foundSecond value
stateHashTable.search(hashIndex, searchState, foundSecond);
// if foundSecond is true and the result of the index values is true..
if (foundSecond && stateHashTable.isItemAtEqual(hashIndex, searchState))
{
cout << "Unable to remove state: " << searchState << endl;
}
else
{
cout << "\nSuccessfully removed " << stateName << " from the hash table. \n" << endl;
cout << "*************************************HASH TABLE*************" << endl;
cout << "STATE NAME" << ", " << "STATE CAPTIAL" << endl;
// call function to print hash table after user input state has been removed
stateHashTable.print();
cout << "\n**********************************************************" << endl;
cout << "\n";
}
system("pause");
}
答案 0 :(得分:1)
感谢下面的评论,只需检查以确保infile >> listingState;在使用listingState之前确实成功解决了我的问题。
将main.cpp中的部分替换为:
resp.content