Alternative version of find_if which finds all, not just the first?

孤者浪人 提交于 2020-01-03 09:48:11

问题


Is there an alternative version of std::find_if that returns an iterator over all found elements, instead of just the first one?

Example:

bool IsOdd (int i) {
  return ((i % 2) == 1);
}

std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);

std::vector<int>::iterator it = find_if(v.begin(), v.end(), IsOdd);
for(; it != v.end(); ++it) {
  std::cout << "odd: " << *it << std::endl;
}

回答1:


You can just use a for loop:

for (std::vector<int>:iterator it = std::find_if(v.begin(), v.end(), IsOdd);
     it != v.end();
     it = std::find_if(++it, v.end(), IsOdd))
{
    // ...
}

Alternatively, you can put your condition and action into a functor (performing the action only if the condition is true) and just use std::foreach.




回答2:


in STL there isn't, but boost offers this funcionality:

boost::algorithm::find_all




回答3:


First always try to come up with typical STL usage itself, you can go for boost as well. Here is more simplified form from the above mentioned answer by Charles.

    vec_loc = find_if(v3.begin(), v3.end(), isOdd);
if (vec_loc != v3.end())
{
    cout << "odd elem. found at " << (vec_loc - v3.begin()) << "and elem found is " << *vec_loc << endl;
    ++vec_loc;
}
for (;vec_loc != v3.end();vec_loc++) 
{
    vec_loc = find_if(vec_loc, v3.end(), isOdd);
    if (vec_loc == v3.end())
        break;
    cout << "odd elem. found at " << (vec_loc - v3.begin()) << "and elem found is " << *vec_loc << endl;
}


来源:https://stackoverflow.com/questions/2344673/alternative-version-of-find-if-which-finds-all-not-just-the-first

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!