Find the index of searching element in an array.

Dec 14, 2016 at 3:40am
closed account (EyqGy60M)
How can we find the index of the searching element in an array? I want to know a built-in function for that. Is there any?
Dec 14, 2016 at 3:59am
What did you mean by searching element?
Dec 14, 2016 at 4:05am
closed account (EyqGy60M)
By searching element i mean the value which i am looking for in the array. For example say we have an array Arr[5] = {1, 2, 3, 4, 5} and i am looking for 3 here in the array Arr. So 3 is the searching element.
Last edited on Dec 14, 2016 at 4:10am
Dec 14, 2016 at 4:29am
std::find returns an iterator, which can convert to an index of an array by subtracting the array start.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    const int SIZE = 6;
    std::string array[SIZE] = { "apple", "pear", "pineapple", "orange", "banana", "grape"}; 
    
    int index = std::find(array, array+SIZE, "orange") - array;
    
    if (index == SIZE)
        std::cout << "not found\n";
    else
        std::cout << array[index] << " was found at index " << index << '\n';
}


Output:
orange was found at index 3


http://www.cplusplus.com/reference/algorithm/find/
Topic archived. No new replies allowed.