В этом посте мы обсудим, как найти индекс первого вхождения заданного элемента в vector в C++.
1. Использование std::find
с std::distance
функция
Самое простое решение — использовать std::find
алгоритм, определенный в <algorithm>
заголовок. Идея состоит в том, чтобы получить индекс, используя std::distance
на итераторе, возвращенном std::find
, который указывает на найденное значение. Мы также можем применить арифметику указателя к итераторам. Следовательно -
оператор тоже будет работать.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = { 7, 3, 6, 2, 6 }; int key = 6; std::vector<int>::iterator itr = std::find(v.begin(), v.end(), key); if (itr != v.cend()) { std::cout << «Element present at index « << std::distance(v.begin(), itr); } else { std::cout << «Element not found»; } return 0; } |
Скачать Выполнить код
результат:
Element present at index 2
2. Использование std::find_if
с std::distance
функция
Мы также можем использовать стандартный алгоритм std::find_if
, который принимает предикат. Это рекомендуемый подход, если поиск должен удовлетворять определенным условиям. Например, найти индекс первой строки, начинающейся с некоторого символа в векторе строк.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <vector> #include <algorithm> struct compare { int key; compare(int const &i): key(i) {} bool operator()(int const &i) { return (i == key); } }; int main() { std::vector<int> v = { 7, 3, 6, 2, 6 }; int key = 6; auto itr = std::find_if(v.cbegin(), v.cend(), compare(key)); if (itr != v.cend()) { std::cout << «Element present at index « << std::distance(v.cbegin(), itr); } else { std::cout << «Element not found»; } return 0; } |
Скачать Выполнить код
результат:
Element present at index 2
3. Наивное решение
Наконец, мы можем написать собственную процедуру для этого, как показано ниже:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = { 7, 3, 6, 2, 6 }; int key = 6; bool found = false; for (int i = 0; i < v.size(); i++) { if (v[i] == key) { std::cout << «Element present at index « << i; found = true; break; } } if (!found) { std::cout << «Element not found»; } return 0; } |
Скачать Выполнить код
результат:
Element present at index 2
Вот и все, что касается нахождения индекса элемента в векторе в C++.
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Given a vector V consisting of N integers and an element K, the task is to find the index of element K in the vector V. If the element does not exist in vector then print -1.
Examples:
Input: V = {1, 45, 54, 71, 76, 17}, K = 54
Output: 2
Explanation :
The index of 54 is 2, hence output is 2.
Input: V = {3, 7, 9, 11, 13}, K = 12
Output: -1
Approach:
Follow the steps below to solve the problem:
- find(): Used to find the position of element in the vector.
- Subtract from the iterator returned from the find function, the base iterator of the vector .
- Finally return the index returned by the subtraction.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using
namespace
std;
void
getIndex(vector<
int
> v,
int
K)
{
auto
it = find(v.begin(), v.end(), K);
if
(it != v.end())
{
int
index = it - v.begin();
cout << index << endl;
}
else
{
cout <<
"-1"
<< endl;
}
}
int
main()
{
vector<
int
> v = { 1, 45, 54, 71, 76, 17 };
int
K = 54;
getIndex(v, K);
return
0;
}
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
10 Jan, 2023
Like Article
Save Article
Something like this, I think. find_if_counted.hpp
:
#ifndef FIND_IF_COUNTED_HPP
#define FIND_IF_COUNTED_HPP
#include <algorithm>
namespace find_if_counted_impl
{
template <typename Func>
struct func_counter
{
explicit func_counter(Func& func, unsigned &count) :
_func(func),
_count(count)
{
}
template <typename T>
bool operator()(const T& t)
{
++_count;
return _func(t);
}
private:
Func& _func;
unsigned& _count;
};
}
// generic find_if_counted,
// returns the index of the found element, otherwise returns find_if_not_found
const size_t find_if_not_found = static_cast<size_t>(-1);
template <typename InputIterator, typename Func>
size_t find_if_counted(InputIterator start, InputIterator finish, Func func)
{
unsigned count = 0;
find_if_counted_impl::func_counter<Func> f(func, count);
InputIterator result = find_if(start, finish, f);
if (result == finish)
{
return find_if_not_found;
}
else
{
return count - 1;
}
}
#endif
Example:
#include "find_if_counted.hpp"
#include <cstdlib>
#include <iostream>
#include <vector>
typedef std::vector<int> container;
int rand_number(void)
{
return rand() % 20;
}
bool is_even(int i)
{
return i % 2 == 0;
}
int main(void)
{
container vec1(10);
container vec2(10);
std::generate(vec1.begin(), vec1.end(), rand_number);
std::generate(vec2.begin(), vec2.end(), rand_number);
unsigned index = find_if_counted(vec1.begin(), vec1.end(), is_even);
if (index == find_if_not_found)
{
std::cout << "vec1 has no even numbers." << std::endl;
}
else
{
std::cout << "vec1 had an even number at index: " << index <<
" vec2's corresponding number is: " << vec2[index] << std::endl;
}
}
Though I feel like I’m doing something silly… :X Any corrections are welcome, of course.
In this article we will different ways to find an element in vector and get its index.
Suppose we have a vector of int i.e.
Advertisements
std::vector<int> vecOfNums = { 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 };
Now we want to find if number 22 exists in vector ? If yes then what’s its index or position in the vector ?
std::vector doesn’t provides any direct function to check if an element exists in vector or not. So let’s see how to do that using STL Algorithms.
Frequently Asked:
- C++: Convert Array to Vector (7 Ways)
- C++: How to initialize two dimensional Vector? – (Initializing 2D Vectors / Matrix)
- Importance of Constructors while using User Defined Objects with std::vector
- Check if all elements in vector are equal in C++
Finding an element in vector using STL Algorithm std::find()
Basically we need to iterate over all the elements of vector and check if given elements exists or not.
This can be done in a single line using std::find i.e.
// Check if element 22 exists in vector std::vector<int>::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22);
It accepts a range and an element to search in the given range. If element is found then it returns an iterator to the first element in the given range that’s equal to given element, else it returns an end of the list.
if (it != vecOfNums.end()) std::cout << "Element Found" << std::endl; else std::cout << "Element Not Found" << std::endl;
If element is found then we can get its index from the iterator i.e.
// Get index of element from iterator int index = std::distance(vecOfNums.begin(), it);
But in practical, we will not have vector of integers always. So, let’s create a generic function for this.
Generic function to find an element in vector of any type
Let’s create a generic function to search an element in any type of vector i.e.
/* Generic function to find an element in vector and also its position. It returns a pair of bool & int i.e. bool : Represents if element is present in vector or not. int : Represents the index of element in vector if its found else -1 */ template < typename T> std::pair<bool, int > findInVector(const std::vector<T> & vecOfElements, const T & element) { std::pair<bool, int > result; // Find given element in vector auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element); if (it != vecOfElements.end()) { result.second = distance(vecOfElements.begin(), it); result.first = true; } else { result.first = false; result.second = -1; } return result; }
This function tells if given element exists in vector and if yes then it also return its position in the vector.
Let’s use this function to find an element in vector i.e.
std::pair<bool, int> result = findInVector<int>(vecOfNums, 45); if (result.first) std::cout << "Element Found at index : " << result.second <<std::endl; else std::cout << "Element Not Found" << std::endl;
Finding an element by custom comparator using std::find_if()
Instead of directly searching by value in the vector , we can search by custom logic too.
Like, in a vector of int check if any multiple of 3 exists i.e.
// Check if any multiple of 3 exists in vector using lambda function as comparator std::vector<int>::iterator it2 = std::find_if(vecOfNums.begin(), vecOfNums.end(), [](const int & val){ if (val % 3 == 0) return true; return false; }); if (it != vecOfNums.end()) std::cout << "Multiple of 3 Found : " << *it2 << std::endl; else std::cout << "Multiple of 3 Not Found" << std::endl;
Finding an element in vector using C++11 Range Based for loop
We can also iterate over the vector using range based for loop and check if element exists or not.
bool found = false; // Iterate over all elements in Vector for (auto & elem : vecOfNums) { if (elem == 22) { found = true; break; } } if(found) std::cout << "Element Found" << std::endl; else std::cout << "Element Not Found" << std::endl;
Complete example is as follows,
#include <iostream> #include <vector> #include <algorithm> /* Generic function to find an element in vector and also its position. It returns a pair of bool & int i.e. bool : Represents if element is present in vector or not. int : Represents the index of element in vector if its found else -1 */ template < typename T> std::pair<bool, int > findInVector(const std::vector<T> & vecOfElements, const T & element) { std::pair<bool, int > result; // Find given element in vector auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element); if (it != vecOfElements.end()) { result.second = distance(vecOfElements.begin(), it); result.first = true; } else { result.first = false; result.second = -1; } return result; } int main() { std::vector<int> vecOfNums = { 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 }; /* Find an element in vector using std::find */ // Check if element 22 exists in vector std::vector<int>::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22); if (it != vecOfNums.end()) { std::cout << "Element Found" << std::endl; // Get index of element from iterator int index = std::distance(vecOfNums.begin(), it); std::cout <<"Index of element in vector : "<<index<<std::endl; } else { std::cout << "Element Not Found" << std::endl; } std::pair<bool, int> result = findInVector<int>(vecOfNums, 45); if (result.first) std::cout << "Element Found at index : " << result.second <<std::endl; else std::cout << "Element Not Found" << std::endl; /* * Finding an element by custom comparator */ // Check if any multiple of 3 exists in vector using lambda function as comparator std::vector<int>::iterator it2 = std::find_if(vecOfNums.begin(), vecOfNums.end(), [](const int & val){ if (val % 3 == 0) return true; return false; }); if (it != vecOfNums.end()) std::cout << "Multiple of 3 Found : " << *it2 << std::endl; else std::cout << "Multiple of 3 Not Found" << std::endl; /* Find an element in vector using c++11 range based for loop */ bool found = false; // Iterate over all elements in Vector for (auto & elem : vecOfNums) { if (elem == 22) { found = true; break; } } if(found) std::cout << "Element Found" << std::endl; else std::cout << "Element Not Found" << std::endl; return 0; }
In this article, we will discuss How to find the index of element in vector in the R programming language. We can find the index of the element by the following functions –
- which()
- match()
Method 1: by using which()
which() function basically returns the vector of indexes that satisfies the argument given in the which() function.
Syntax: which(condition)
Example 1: We first create the vector of values (0,1,2,3,4,5,6,7,8,9), and then we try to get the index value of the element “5” with the help of which() function.
So, the condition which we used to get the index of element 5 is:
which(v == 5)
Code:
R
v <-
c
(0, 1, 2, 3, 4,
5, 6, 7, 8, 9)
which
(v == 5)
Output:
6
Example 2: In this example, we will try to get the index of the element which is repeated.
So, we will create a vector of repeated elements (1,2,4,1,6,2,4,4,6) now we try to find the index of 4 and which function returns a function that holds every index value of 4 elements. In our case that is 3 7 8
R
v <-
c
(1, 2, 4, 1, 6, 2, 4, 4, 6)
which
(v == 4)
Output:
3 7 8
Example 3: In this example, we will try to get the first index of the element which is repeated.
So, to do this we will just use the [1] to basically get the first element of the vector created by the which() function. In our case, we will try to get the first index of element 4
R
v <-
c
(1, 2, 4, 1, 6, 2, 4, 4, 6)
which
(v == 4)[1]
Output:
3
Example 4: In this example, we will try to get the index of the multiple elements using which() function.
So, to do this we will just give the values as an argument to the which() function. In our case, we will try to get the index of elements 4 and 6. So, they together used as a vector with the %in% and which function returns the vector of the index of both the elements.
R
v <-
c
(1, 2, 4, 1, 6,
2, 4, 4, 6)
which
(v %
in
%
c
(4, 6))
Output:
[1] 3 5 7 8 9
Method 2: by using match()
match() function basically returns the vector of indexes that satisfies the argument given in the match() function.
Syntax: match(element, vector_name)
Example 1: In our case, we first create the vector of values (0,1,2,3,4,5,6,7,8,9), and then we try to get the index value of the element “5” with the help of the match() function.
So, the condition which we used to get the index of element 5 is:
match(5,v)
Code:
R
v <-
c
(0, 1, 2, 3, 4,
5, 6, 7, 8, 9)
match
( 5 , v )
Output:
6
Example 2: In this example, we will try to get the first index of the multiple elements using the match() function.
So, to do this we will just give the values as an argument to the match() function. In our case, we will try to get the index of elements 4 and 6. So, they together used as a vector which function returns the vector of the first index of both the elements.
R
v <-
c
( 1, 2, 4, 1,
6, 2, 4, 4, 6)
match
(
c
( 4, 6), v)
Output:
3 5
Last Updated :
16 May, 2021
Like Article
Save Article