Find all strings that are less than 4 characters long : find if « STL Algorithms Non modifying sequence operations « C++






Find all strings that are less than 4 characters long

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

using namespace std;

bool is_short_str(string str);

int main()
{
  vector<string> v;
  vector<string>::iterator itr;

  v.push_back("one");
  v.push_back("two");
  v.push_back("three");
  v.push_back("four");
  v.push_back("five");
  v.push_back("six seven");

  for(unsigned i=0; i < v.size(); ++i)
    cout << v[i] << endl;

  itr = v.begin();
  do {
    itr = find_if(itr, v.end(), is_short_str);
    if(itr != v.end()) {
      cout << "Found " << *itr << endl;
      ++itr;
    }
  } while(itr != v.end());
  return 0;
}

// Return true if the string is 3 characters or less.
bool is_short_str(string str)
{
  if(str.size() <= 3) return true;
  return false;
}
  
    
  








Related examples in the same category

1.Use find_if to find first element divisible by 3
2.Use find_if to find first element greater than 3
3.map: find_if
4.std::find_if with predicate