【c++】 vector 查找/二分查找/查找Pair


在vector中查找元素方法很多,比较简单的是利用标准库中提供的方法来查找。
对vector中的pair进行多次find操作

1. find()

std::vector<int>::iterator iter=find(_adjlists.begin(), _adjlists.end(), v);
if(iter == _adjlists.end()){ 
	// 没查到
}
else{
	// 找到了
}

2. 二分查找(lower_bound)

C++标准库里的二分查找算法剖析
对于需要多次查询,为了提高查询效率,可以考虑先排序,然后使用二分查找。
lower_bound返回的是[v.begin(), v.end()]中第一个大于或等于查找值的迭代器,所以我们需要额外判断元素是否找到且真的相等。
直接看例子:

#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> vec;
    for(int i = 10; i > 0; i--)
        vec.push_back(i);
    for(int i : vec){
        std::cout << i << " ";
    }
    std::cout << std::endl;
    std::sort(vec.begin(), vec.end());
    for(int i : vec){
        std::cout << i << " ";
    }
    std::cout << std::endl;

    auto first = std::lower_bound(vec.begin(), vec.end(), 2);
    if(!(first == vec.end()) && (*first == 2)){
        std::cout << "find:" << *first << std::endl;
    }
    else{
        std::cout << "no find." << std::endl;
    }

    first = std::lower_bound(vec.begin(), vec.end(), 0);
    if(!(first == vec.end()) && (*first == 0)){
        std::cout << "find:" << *first << std::endl;
    }
    else{
        std::cout << "no find." << std::endl;
    }

    first = std::lower_bound(vec.begin(), vec.end(), 11);
    if(!(first == vec.end()) && (*first == 11)){
        std::cout << "find:" << *first << std::endl;
    }
    else{
        std::cout << "no find." << std::endl;
    }
}

运行结果:

10 9 8 7 6 5 4 3 2 1 
1 2 3 4 5 6 7 8 9 10 
find:2
no find.
no find.

3. 查找Pair

如果vector中的元素时Pair<>时,可以参考下面的例子:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Functor
template<class vertex_t, class value_t>
class isEqualALL {
public:
    explicit isEqualALL(vertex_t node) : node(node) {}
    bool operator() (const std::pair<vertex_t, value_t>& element) const {
        return element.first == node;
    }
private:
    const vertex_t node;
};

int main(void)
{

    vector<pair<int, int>> sortList;
    sortList = {
        pair<int, int>(1, 100),
        pair<int, int>(2, 200),
        pair<int, int>(3, 300),
        pair<int, int>(4, 400),
    };

    auto it = std::find_if( sortList.begin(), sortList.end(), isEqualALL<int, int>(2));

    if (it != sortList.end()) {
        cout << it->first << " " << it->second << endl;
    }

    return 0;
}

运行结果

2 200

版权声明:本文为qq_39451578原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。