Pointers, Structs, Vectors Problems

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.

#include <iostream>
#include <vector>
#include <string>
#include <fstream>

using namespace std;

struct CountWords
{
string *pstring;
int vcount;
};

void ReadFileOfWords(vector<CountWords>&);
void AddWordToVector(string, vector<CountWords>&);

int main ()
{
vector<CountWords> vec;

ReadFileOfWords(vec);

}

void ReadFileOfWords(vector<CountWords> &vec)
{
ifstream inputFile( "CountWords.txt" );
string temp;

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
1
2
for(int i=0; i<vec.size(); ++i)
   delete vec[i].pstring;



Why not you created a structure of
1
2
3
4
5
struct CountWords
{
string pstring;   //not a pointer!
int vcount;
};


This would save you from manual dynamic memory allocation with "new".

Must you use std::vector? With std::map this is solved more beautiful and fast.
That worked!! Awesome! Thank you!

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.
Last edited on
Topic archived. No new replies allowed.