Skip to content

Instantly share code, notes, and snippets.

@thevtm
Created June 3, 2013 00:46
Show Gist options
  • Save thevtm/5695553 to your computer and use it in GitHub Desktop.
Save thevtm/5695553 to your computer and use it in GitHub Desktop.
Find and iterate through a range.
template<class _InIt, class _Ty, class _Fn1> inline
void find_iterate(_InIt _First, _InIt _Last, const _Ty& _Val, _Fn1 _Func)
{ // find and perform a function if equals to _Val
for (_First = std::find(_First, _Last, _Val); _First != _Last; _First = std::find(++_First, _Last, _Val))
_Func(*_First);
}
template<class _InIt, class _Pr, class _Fn1> inline
void find_if_iterate(_InIt _First, _InIt _Last, _Pr _Pred, _Fn1 _Func)
{ // find and perform a function satisfying _Pred
for (_First = std::find_if(_First, _Last, _Pred); _First != _Last; _First = std::find_if(++_First, _Last, _Pred))
_Func(*_First);
}
template<class _InIt, class _Pr, class _Fn1> inline
void find_if_not_iterate(_InIt _First, _InIt _Last, _Pr _Pred, _Fn1 _Func)
{ // find and perform a function not satisfying _Pred
for (_First = std::find_if_not(_First, _Last, _Pred); _First != _Last; _First = std::find_if_not(++_First, _Last, _Pred))
_Func(*_First);
}
void find_iterate_tests()
{
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 0);
std::cout << "find_iterate_tests()" << std::endl;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// Transform 3 to -1
find_iterate(v.begin(), v.end(), 3,
[] (int& i) { i = -1; });
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
void find_if_iterate_tests()
{
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 0);
std::cout << "find_if_iterate_tests()" << std::endl;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// Transform all odd numbers to -1
find_if_iterate(v.begin(), v.end(),
[] (const int& i) { return i % 2; },
[] (int& i) { i = -1; });
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
void find_if_not_iterate_tests()
{
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 0);
std::cout << "find_if_not_iterate_tests()" << std::endl;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// Transform all even numbers to -1
find_if_not_iterate(v.begin(), v.end(),
[] (const int& i) { return i % 2; },
[] (int& i) { i = -1; });
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment