Answers for "c++ vector search"

C++
5

vector.find()

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();
else
   do_that();
Posted by: Guest on July-09-2020
0

vector search by element

#include <vector> // vector 
#include <algorithm> // find 
#include <iostream> // cout 
using namespace std;
int main()
{
    vector<int> nums = {1,2,3,4,5,6,7,8,9};
    bool isSorted = is_sorted(nums.begin(), nums.end());
    if(isSorted){
        cout << "Using binary search: " << endl;
        if(binary_search(nums.begin(), nums.end(), 9))
            cout << "found it" << endl;
        else
            cout << "not here" << endl;
    }
    else{
        cout << "Using std::find";
        if(std::find(nums.begin(), nums.end(), 9) != nums.end())
            cout << "found it" << endl;
        else
            cout << "not here" << endl;
    }
}
Posted by: Guest on August-21-2021

Browse Popular Code Answers by Language