Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ vector element search

#include <algorithm>
#include <vector>
vector<int> vec; 
//can have other data types instead of int but must same datatype as item 
std::find(vec.begin(), vec.end(), item) != vec.end()
Comment

c++ find element in vector

auto it = find(vec.begin(),vec,end(), item)!
if(it != vec.end()){
 	 int index = it - vec.begin();
}
Comment

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;
    }
}
Comment

find element in vector


    it = find (vec.begin(), vec.end(), ser);
    if (it != vec.end())
    {
        cout << "Element " << ser <<" found at position : " ;
        cout << it - vec.begin() << " (counting from zero) 
" ;
    }
    else{
        cout << "Element not found.

";
    }
Comment

PREVIOUS NEXT
Code Example
Cpp :: prime number in c++ 
Cpp :: cout was not declared in this scope 
Cpp :: remove element from vector on condition c++ 
Cpp :: how to read a line from the console in c++ 
Cpp :: Sort array using inbuilt sort function in decreasing order 
Cpp :: save all output in log file c cpp 
Cpp :: default access modifier in c++ in struct 
Cpp :: how to change string to lowercase and uperCase in c++ 
Cpp :: arduino notone 
Cpp :: time delay in c++ 
Cpp :: dynamically generating 2d array in cpp 
Cpp :: c++ mst kruskal 
Cpp :: create random vectors c++ 
Cpp :: how to run a c++ file from terminal linux 
Cpp :: delete last char of string c++ 
Cpp :: how to split a string into words c++ 
Cpp :: strip space from string cpp 
Cpp :: lerp function c++ 
Cpp :: tuple c++ 
Cpp :: c++ return multiple values 
Cpp :: number of lines in c++ files 
Cpp :: c++ function 
Cpp :: c++ vector pop_back 
Cpp :: read comma separated text file in c++ 
Cpp :: C++ cin cout 
Cpp :: ViewController import 
Cpp :: continue c++ 
Cpp :: cout hex c++ 
Cpp :: c++ code for bubble sort 
Cpp :: how to input a vector when size is unknown 
ADD CONTENT
Topic
Content
Source link
Name
9+1 =