-
reading words into set
i am trying to read words from a file i have "words.txt" into a set. the code i have written compiles and prints to screen fine but my question is what makes something a "set"? i mean i named my class "set" but beyond that how do i know it is a set?
code for main:
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include "set.h"
using namespace std;
int main()
{
set<string> object;
string word, search;
ifstream infile;
infile.open("words.txt");
while (infile >> word)
{
object.readWords(word);
}
object.printWords();
cout << "Enter word to search for: ";
cin >> search;
object.search(search);
return 0;
}
code for class:
Code:
#ifndef SET_H
#define SET_H
#include <list>
#include <algorithm>
using namespace std;
template <class T>
class set
{
public:
void readWords(T& word);
void printWords();
void search(T& search);
private:
list<T> setList;
};
template <class T>
void set<T>::readWords(T &word)
{
setList.insert(setList.end(), word);
}
template <class T>
void set<T>::printWords()
{
list<T>::iterator iter;
for (iter = setList.begin(); iter != setList.end(); iter++)
cout << *iter << endl;
}
template <class T>
void set<T>::search(T &search)
{
if (binary_search(setList.begin(), setList.end(), search))
cout << search << " was found in the set. " << endl;
else
cout << "That word was not found. " << endl;
}
#endif
-
You don't have a set, you have a list. The point of a set is that every object can only appear once in the set, so if you try to add "the" to the set and "the" is already there, then it doesn't actually get added.
set is built into the STL, unless the point is to write your own.
-
is this way correct?
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
void wordTest(string);
int main()
{
set<string> myset;
set<string>::iterator iter;
string word, search;
ifstream infile;
infile.open("words.txt");
while (infile >> word)
{
myset.insert(word);
}
for (iter = myset.begin(); iter != myset.end(); iter++)
cout << *iter << endl;
cout << "Enter word to search for: ";
cin >> search;
iter = myset.find(search);
if (iter == myset.end())
cout << "That word is not in the set" << endl;
else
cout << *iter << " is in the set" << endl;
wordTest(search);
return 0;
}
-
Looks fine, but just a few of recommendations:
- Always check that the file was actually opened and that an error doesn't occur while reading from the file (use istream::fail( )).
- wordTest should probably take a const reference to (as opposed to a copy of) a string. It's much more efficient.