I need to write a program that reads in a text file of 1000 words, stores the address of each word into a different element in a vector of pointers, and store each unique word into an array of strings. I understand the principles behind vectors and pointers and arrays, I'm just having trouble knowing where to start and what I am doing wrong. Any suggestions on what to do next?
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
#include<vector>
using namespace std;
const int SIZE=200;
int main()
{
ifstream fin;
fin.open("word.txt");
if(fin.fail())
{cout<<"File did not open. Shutting down...\n\a";
return 0;
}//if
string word;
int currentSize=1;
string unique[SIZE];
A vector of pointers is rarely a useful idea, and parallel arrays are even less common. What do you need this data structure for? How is it going to be used?
If you're looking to list all unique words, consider a set:
Yes.. It's not very practical. It's an assignment designed to test my knowledge of pointers and vectors. It's very limited in its application. I'm struggling the most with the best way to compare the strings as it reads in each word to determine whether the word is unique and has already been stored in the array or whether it is a duplicate of a previous word.
It sounds a bit like the Flyweight pattern but thats not important.
The basic flow would be something like:
Read a word from the file.
Add the word to the array and get a pointer to the element in the array
Store the pointer in the vector.
Breaking Down the Add the word to the array...
With the string you loop through (iterate) the array comparing the the string to the element
if the string is matched to one in the array take a pointer to that element
else add the string to the next available position in the array and take a pointer to that element.
Consider stepping through your loop with a debugger and observing the results of each line. That should tell you at least whether it stores unique or all strings in the array,
I think you're shooting for something like
1 2 3 4 5 6 7
int count = 0;
for(string word; fin >> word && count < SIZE; ++count)
{
ptr.push_back(find(unique, unique+count, word));
if(ptr.back() == unique+count)
unique[count] = word;
}
Although you could improve the efficiency of the search for duplicates by using an ordered container instead of array.