Click to See Complete Forum and Search --> : vectors and find
stober
October 9th, 2002, 12:00 PM
how does the find STL function work with strings? The code below doesn't work correctly. The purpose is to build a list of unique words. If the word is not in the vector, then add it.
void foo()
{
fstream stream;
vector<string> theList;
string oneWord;
stream.open(...); // open the file for reading
while( !stream.eof())
{
stream >> oneWord;
vector<string>::iterator pos;
pos = find( theList.begin(), theList.end(), oneWord);
if(pos == NULL)
theList.push_back(oneWord);
}
}
jwbarton
October 9th, 2002, 12:14 PM
First, find returns an iterator representing the item or end() if it is not found. So you need to check for pos == theList.end() instead of NULL.
Second, this is probably not the best choice of containers for doing this operation. A better choice might be to use std::set (this might not be the best choice, but it will certainly be better than using a vector).
Best regards,
John
Federal102
October 9th, 2002, 12:26 PM
std::set would definitely be the way to go. Elements are automatically sorted and duplicates are not permitted.
stober
October 9th, 2002, 12:59 PM
Thanks for both your replies. Here are the changes that works. Any other suggestions for improvement?
set<string> theArray;
void foo(string& str)
{
string oneWord;
fstream stream;
stream.open(str.c_str(), ios::in);
while(!stream.eof())
{
stream >> oneWord;
set<string>::iterator pos;
pos = theArray.find(oneWord);
if(pos == theArray.end() )
{
theArray.insert(oneWord);
}
}
stream.close();
}
jwbarton
October 9th, 2002, 01:04 PM
Yes, don't bother checking if the item is in the set before the insert. The set will take care of that for you. So, just do the following:
set<string> theArray;
void foo(string& str)
{
string oneWord;
fstream stream;
stream.open(str.c_str(), ios::in);
while(!stream.eof())
{
stream >> oneWord;
theArray.insert(oneWord);
}
stream.close();
}
Best regards,
John
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.