Znajdywanie wyrazów

0

Mam problem z napisaniem programu, w ktorym wyszukuje wyrazy w tekscie, które nie znajdują się w pliku z listą wyrazów - ułożona alfabetycznie. Moj tekst w którym szukam, wyrazów nie wystepujacych w drugim pliku zamieszczony jest w vectorze (string). Jak zrobic to dosyć prosto i korzystnie, aby program nie działał zbyt długo?

2

Zapoznaj się z: unordered_set<string>

0

Miałem iść spać, ale prosz:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <unordered_set>

using namespace std;

vector<string> findWords( const vector<string> &wordsToSearchIn, 
                          const unordered_set<string> &wordsToReject )
{
    vector<string> result( wordsToSearchIn.size() )	;
    auto pred = [wordsToReject]( const string &word )
				               {
				                   return wordsToReject.find( word ) == wordsToReject.end();
				               };
    
    auto it = copy_if( wordsToSearchIn.begin(),
             		   wordsToSearchIn.end(),
                       result.begin(),
                       pred );
             
    result.resize( distance( result.begin(), it) );
    
    return result;
}

int main() 
{
	vector<string> wordsToSearchIn{ "siema", "herbata", "krzeslo" };
	unordered_set<string> wordsToReject{ "herbata" };
	
	auto result = findWords( wordsToSearchIn, wordsToReject );
	
	for( const auto &word : result )
		cout<<word<<"\n";
		
	return 0;
}

http://ideone.com/nyOyIs

1

Użycie back_inserter() trochę upraszcza, zaś przekazanie do pred przez referencje mocno przyśpiesza:

#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <unordered_set>
using namespace std;
 
int main() 
  {
   vector<string> input { "siema", "herbata", "krzeslo" };
   unordered_set<string> drop { "herbata" };
   vector<string> result;
   copy_if
     (
      begin(input),end(input),back_inserter(result),
      [&drop](const string &s) { return drop.find(s)==drop.end(); } 
     );
   ostream_iterator<string> iout(cout,"\n");
   copy(begin(result),end(result),iout);
   return 0;
  }

1 użytkowników online, w tym zalogowanych: 0, gości: 1