CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jun 2002
    Posts
    1,417

    vectors and find

    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.

    Code:
    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);
          }
    }

  2. #2
    Join Date
    Jan 2001
    Posts
    253
    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

  3. #3
    Join Date
    Jun 2002
    Location
    Boston, MA
    Posts
    139
    std::set would definitely be the way to go. Elements are automatically sorted and duplicates are not permitted.

  4. #4
    Join Date
    Jun 2002
    Posts
    1,417
    Thanks for both your replies. Here are the changes that works. Any other suggestions for improvement?

    Code:
    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();
    }

  5. #5
    Join Date
    Jan 2001
    Posts
    253
    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:

    Code:
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured