Find last element in std::vector which satisfies a condition

痞子三分冷 提交于 2020-01-03 04:53:27

问题


I have this requirement to find the last element in the vector which is smaller than a value.

Like find_first_of but instead of first i want last. I searched and found that there is no find_last_of but there is find_first_of.

Why is that so? Is the standard way is to use find_first_of with reverse iterators?


回答1:


Use reverse iterators, like this:

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> v{1,2,42,42,63};
  auto result = std::find_if(v.rbegin(), v.rend(),
                             [](int i) { return i == 42; });

  std::cout << std::distance(result, v.rend()) << '\n';
}

Live demo.




回答2:


This is how it is done with reverse iterators:

std::vector<int> vec = {2,3,10,5,7,11,3,6};  

//below outputs '3':
std::cout << *(std::find_if(vec.rbegin(), vec.rend(), [](int i) { return i < 4; })); 



回答3:


Just one thing. Be careful with the predicate if you're looking to find the tail-end of the range which includes the predicated element:

int main()
{
    std::vector<int> x { 0, 1, 2, 3, 4, 5 };

    // finds the reverse iterator pointing at '2'
    // but using base() to convert back to a forward iterator
    // also 'advances' the resulting forward iterator.
    // in effect, inverting the sense of the predicate to 'v >= 3'
    auto iter = std::find_if(std::make_reverse_iterator(x.end()),
                 std::make_reverse_iterator(x.begin()),
                 [](auto& v) { return v < 3; }).base();

    std::copy(iter,
              x.end(),
              std::ostream_iterator<int>(std::cout, ", "));
}

result:

3, 4, 5,



回答4:


From ZenXml:

template <class BidirectionalIterator, class T> inline
BidirectionalIterator find_last(const BidirectionalIterator first, const 
BidirectionalIterator last, const T& value)
{
    for (BidirectionalIterator it = last; it != first;) 
    //reverse iteration: 1. check 2. decrement 3. evaluate
    {
        --it; //

        if (*it == value)
            return it;
    }    
    return last;
}


来源:https://stackoverflow.com/questions/39165432/find-last-element-in-stdvector-which-satisfies-a-condition

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