×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

How to check whether an element exists in a vector in C++ STL?

Here, we are going to learn how to find, if an elements exists in a vector in C++ STL?
Submitted by IncludeHelp, on June 16, 2019

Given a vector and an element to be searched in the vector.

Checking whether an element exists in a vector

To check whether an elements exists in a vector or not – we use find() function. find() function takes 3 arguments.

Syntax

find(InputIterator first, InputIterator last, const T& element);

Parameters

  • InputIterator first – an iterator pointing to the first elements (or elements from where we have to start the searching).
  • InputIterator last – an iterator pointing to the last elements (or elements till then we have to find the element).
  • element – and elements of same type to be searched.

If the element exists – it returns an iterator to the first element in the range that compares equal to element (elements to be searched). If the element does not exist, the function returns last.

C++ STL program to check whether given element exists in the vector or not

// C++ STL program to check whether given
// element exists in the vector or not
#include <iostream>
#include <vector> // for vectors
#include <algorithm> // for find()
using namespace std;

int main()
{

    int element; //element to be searched
    // Initializing a vector
    vector<int> v1{ 10, 20, 30, 40, 50 };

    // input element
    cout << "Enter an element to search: ";
    cin >> element;

    vector<int>::iterator it = find(v1.begin(), v1.end(), element);
    if (it != v1.end()) {
        cout << "Element " << element << " found at position : ";
        cout << it - v1.begin() + 1 << endl;
    }
    else {
        cout << "Element " << element << " does not found" << endl;
    }

    return 0;
}

Output

First run:
Enter an element to search: 30
Element 30 found at position : 3

Second run:
Enter an element to search: 60
Element 60 does not found

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.