My code is below. I'm pretty sure my issues are spanning my my .resize(). It's possible I'm doing my hashing completely wrong too, but it was right at one point. This code wont run at all right now, but it compiles. Is there a better way to go about sizing my container?

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <list>
using namespace std;

typedef vector<list<string> > hash_set;

void hashInsert(hash_set &vtr, string word);
int getHash(string word);

int main()
{
	int size = 0;
	string word;

	hash_set vtr;

	ifstream firstfile ("doc1.txt");
	if (firstfile)
	{
		while ( firstfile >> word )
		{
			size++;
			vtr.resize(2*size);
	//		hashInsert(vtr, word);
		}
		firstfile.close();
	}
	else cout << "Unable to open file";

	ifstream samefile ("doc1.txt");
	if (samefile)
	{
		while ( samefile >> word )
		{
			hashInsert(vtr, word);
		}
		samefile.close();
	}
	else cout << "Unable to open file";
	

	for (size_t vtrIndex=0; vtrIndex < vtr.size(); ++vtrIndex)
	{
		for (list<string>::iterator it = vtr[vtrIndex].begin(); it != vtr[vtrIndex].end(); ++it) 
		{
			cout << *it << " " << vtrIndex << '\n';
		}
	}

	return 0;
}



void hashInsert(hash_set &vtr, string word)
{
	vtr[getHash(word)].push_back(word);
}

int getHash(string word)
{
	int output;
	int i;

	output = word[word.size()-1];

	for (i = (word.size()-2); i >= 0; i--)
	{
		output = (128*output + word[i]) % 127;
	}

	return output;
}

Recommended Answers

All 2 Replies

Something more than "This code wont run at all right now" would be helpful. :)
I don't see why you would want to keep resizeing your vector. It's simply not needed to start with. I would suggest just comment out that code, let vector resize by itself, later when things work you can optimize.
Anyway I don't think there is any issue with resize(). Also given the way you're storing teh data (vector<list<..>> ) I don't see any problems that your hash function can cause.
-------------
O now I saw your hashing code more closely. Well, given that you have done this:
output = (128*output + word) % 127;
It's always ensured that getHash() returns something between 0-127. So line 20 to 31 in your original code can be replaced by vtr.resize(128) ;

Thanks for the response, I figured out what i was doing with the size. I ended up making it the size of the input file (how many words it contained). After i got my other functions working properly, it worked like a charm. Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.