I am trying to write a program incorporating structs, pointers and vectors and am having a hard time getting code to work. I am creating of vector of structs. I need to create a vector entry for each word and also count the occurrences of each word in teh file. The program bombs when I am trying to search the vector to see if the word exists in the vector. Maybe I am completely off base here, but I am struggling with this one. I am also not sure how to deallocate the memory for the dynamic string being created for pHstring. I have read that I should use delete [] vectorname or free vectorname, but those did not seem to work.
while (!inputFile.eof())
{
inputFile >> temp;
AddWordToVector(temp, vec);
}
inputFile.close();
}
void AddWordToVector (string temp, vector<CountWords> &vec)
{
bool status = false;
CountWords TestCount;
int count = 0;
//test if vector is empty
if (vec.empty())
{
status = false;
}
else
{
//test if the word already exists in the vector
for (count = 0; count < vec.size(); count++)
{
//program fails when it reaches the line below
if (*(vec.at(count).pstring) == temp)
{
status = true;
break;
}
}
}
if (status)
{
//if word exists in vector, increment by one
vec.at(count).vcount =+ 1;
}
else
{
//add new instance of struct
vec.push_back(TestCount);
TestCount.pstring = new string(temp);
TestCount.vcount = 1;
}
//add new instance of struct
vec.push_back(TestCount);
TestCount.pstring = new string(temp);
TestCount.vcount = 1;)
You should build the instance TestCount BEFORE you push_back it into the vector. Posterior changing like TestCount.pstring = new string(temp); would change the local variable TestCount, but not newly added element of the vector.
At the end of the program you should free all memory you have allocated with "new" operator.
If all the instances in the vec were build correctly than you shoul do
I used a pointer so that I can become more familiar with them. I haven't worked with them very much with structs, so I wanted to give it a shot. Now it makes sense! It is definitely easier not using a pointer.