I have following code:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <functional>
using namespace std;
typedef istream_iterator<string> is_it;
typedef vector<string>::iterator v_str_it;
int main()
{
int i = 4;
ifstream ifstr("1.txt");
is_it ifstrm(ifstr);
is_it eof;
vector<string> v_str(ifstrm, eof);
v_str_it vsit = v_str.begin();
while( (vsit = find_if(vsit, v_str.end(),
bind2nd(equal_to<string>(), i ))) != v_str.end())
{
cout << *vsit << endl;
++vsit;
}
return 0;
}
As far as I understand in find_if(vsit, v_str.end(), bind2nd(equal_to<string>(), i ) i should use const char like "sometext" instead of int i. But how can i find words with length equal to 4 e.g. ? I’m confused and need some advice.
find_ifwill only return the first item in the sequence that satisfies the predicate.For this you really want a lambda and if you are using C++11. This will look something like:
(Not sure of the exact syntax).
To create a “functor” which is the simplest here you might do:
Within your vector you would now use
std::find_if( v.begin(), v.end(), CompareStringLength(i) );to get the first element. To find all of them there is no
std::copy_ifto copy them into another vector so you’d actually have to create a different predicate that returns the opposite and use remove_copy_if which does exist or write your own copy_if algorithm.