C++ : How to find an element in vector and get its index ?

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.

C++

 

1

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.

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.

C++

 

1

2

// 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.

C++

 

1

2

3

4

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.

C++

 

1

2

// 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.

C++

 

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

/*

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.

C++

 

1

2

3

4

5

6

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.

C++

 

1

2

3

4

5

6

7

8

9

10

11

12

// 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.

C++

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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,

C++

 

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

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

#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;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值