using STL to find all elements in a vector

前端 未结 7 655
时光取名叫无心
时光取名叫无心 2020-12-31 08:01

I have a collection of elements that I need to operate over, calling member functions on the collection:

std::vector v;
... // vector is popula         


        
7条回答
  •  被撕碎了的回忆
    2020-12-31 08:18

    std::vector v, matches;
    std::vector::iterator i = v.begin();
    MyPred my_pred;
    while(true) {
        i = std::find_if(i, v.end(), my_pred);
        if (i == v.end())
            break;
        matches.push_back(*i);
    }
    

    For the record, while I have seen an implementation where calling end() on a list was O(n), I haven't seen any STL implementations where calling end() on a vector was anything other than O(1) -- mainly because vectors are guaranteed to have random-access iterators.

    Even so, if you are worried about an inefficient end(), you can use this code:

    std::vector v, matches;
    std::vector::iterator i = v.begin(), end = v.end();
    MyPred my_pred;
    while(true) {
        i = std::find_if(i, v.end(), my_pred);
        if (i == end)
            break;
        matches.push_back(*i);
    }
    

提交回复
热议问题