find index of element in vector c++
// C++ program to find the index
// of an element in a vector
#include <bits/stdc++.h>
using namespace std;
// Function to print the
// index of an element
void getIndex(vector<int> v, int K)
{
auto it = find(v.begin(), v.end(), K); // returns iterator to element K
// If element was found
if (it != v.end()) {
// calculating the index
// of K
int index = distance(v.begin(), it);
cout << index << endl;
}
else {
// If the element is not
// present in the vector
cout << "-1" << endl;
}
}
// Driver Code
int main()
{
// Vector
vector<int> v = { 1, 45, 54, 71, 76, 17 };
// Value whose index
// needs to be found
int K = 54;
getIndex(v, K);
return 0;
}
// CPP program to illustrate
// std::find
// CPP program to illustrate
// std::find
#include<bits/stdc++.h>
int main ()
{
std::vector<int> vec { 10, 20, 30, 40 };
// Iterator used to store the position
// of searched element
std::vector<int>::iterator it;
// Print Original Vector
std::cout << "Original vector :";
for (int i=0; i<vec.size(); i++)
std::cout << " " << vec[i];
std::cout << "\n";
// Element to be searched
int ser = 30;
// std::find function call
it = std::find (vec.begin(), vec.end(), ser);
if (it != vec.end())
{
std::cout << "Element " << ser <<" found at position : " ;
std::cout << it - vec.begin() << " (counting from zero) \n" ;
}
else
std::cout << "Element not found.\n\n";
return 0;
}