vector searching

so basically i have a load of words in my vector and i need to find words that contain "ly" how do i go about trying to do a find_if algorithm. also is it possible for me to use the same algorithm to find words that are longer than 7 letter by simply changing the the varible from ly to >= 7

please help
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;


string tolower( string word )
{
   for ( char &c : word ) c = tolower( c );
   return word;
}


struct Item
{
   string word;
   string definition;
   string type;
};

istream & operator >> ( istream &in, Item &item )
{
   getline( in >> ws, item.word ) && getline( in, item.definition ) && getline( in, item.type );
   return in;
}

ostream & operator << ( ostream &out, const Item &item )
{
   return out << item.word << '\n' << item.definition << '\n' << item.type << '\n';
}


using Dictionary = vector<Item>;


void filter( const string &title, const Dictionary &dict, bool (*f)( Item ) )
{
   cout << title << '\n';
   for ( Item item : dict ) if ( f( item ) ) cout << item.word << '\n';
}


int main()
{
   Dictionary dict;
   ifstream in( "dictionary.txt" );
   for ( Item item; in >> item; ) dict.push_back( item );

   sort( dict.begin(), dict.end(), []( Item &a, Item &b ){ return tolower( a.word ) < tolower( b.word ); } );

   cout << "Your original dictionary is:\n";
   for ( const Item &item : dict ) cout << item << '\n';

   string title = "\n\nContains 'le':";
   auto test1 = []( Item item ){ return tolower(item.word).find( "le" ) != string::npos; };
   filter( title, dict, test1 );

   title = "\n\nAt least 9 letters:";
   auto test2 = []( Item item ){ return item.word.size() >= 9; };
   filter( title, dict, test2 );
}


Your original dictionary is:
abaca
The Manila-hemp plant (Musa textilis); also its fiber. See Manila hemp under Manila.
n

abacinate
To blind by a red-hot metal plate held before the eyes.
v

abacination
The act of abacinating.
n

bleeping
damned.
adj

blemishless
Without blemish; spotless.
adj

blendous
Pertaining to consisting of or containing blende.
adj



Contains 'le':
bleeping
blemishless
blendous


At least 9 letters:
abacinate
abacination
blemishless




Last edited on
Your code already finds words that contain "le" and words whose length is >= 9. It's trivial to change to code to find words containing "ly" and words whose length is >= 7
1
2
3
4
copy_if(words.begin(), words.end(), back_inserter(ly), [](const string& x) { return x.find("ly") != string::npos; });//looks for words with "ly" in them
for (const string& s : ly) cout << "  " << s << '\n';//Prints it out



Topic archived. No new replies allowed.