Finding index of an array element??
-
Hi, Is there any function that returns an index of a particular element in a numeric array. Thanks P.S. I am looking for an equivalent of MATLAB's find() function.
You can use a combination of std::find[^] and std::distance[^] in order to search for an element and get its index. The standard algorithms will work both on standard containers and arrays. Here is a quick example for you, which demonstrates the usage of
std::find
andstd::distance
withstd::vector
and regular array:// Prepare the test array int arr\[\] = {31, 53, 7, 9, 45, 20}; const int size = (sizeof(arr) / sizeof(arr\[0\])); int\* arr\_beg = arr; int\* arr\_end = arr + size; // Prepare the test vector std::vector<int> vec; std::copy(arr, arr + size, std::back\_inserter(vec)); // Search the array std::cout << "\\n Searching the array for element with value 7..."; int\* res1 = std::find(arr, arr + size, 7); if(res1 != arr\_end) std::cout << "\\n The element is found at index: " << std::distance(arr\_beg, res1); else std::cout << "\\n The element is not found"; std::cout << "\\n Searching the array for element with value 8..."; int\* res2 = std::find(arr, arr + size, 8); if(res2 != arr\_end) std::cout << "\\n The element is found at index: " << std::distance(arr\_beg, res2); else std::cout << "\\n The element is not found"; // Search the vector std::cout << "\\n Searching the vector for element with value 7..."; std::vector<int>::iterator it1 = std::find(vec.begin(), vec.end(), 7); if(it1 != vec.end()) std::cout << "\\n The element is found at index: " << std::distance(vec.begin(), it1); else std::cout << "\\n The element is not found"; std::cout << "\\n Searching the vector for element with value 8..."; std::vector<int>::iterator it2 = std::find(vec.begin(), vec.end(), 8); if(it2 != vec.end()) std::cout << "\\n The element is found at index: " << std::distance(vec.begin(), it2); else std::cout << "\\n The element is not found";
I hope this helps. :)
-
Hi, Is there any function that returns an index of a particular element in a numeric array. Thanks P.S. I am looking for an equivalent of MATLAB's find() function.
you can use std::find function.you need to include algorithm header file for example if you have a vector containing some integers you can call it like this vector::iterator the_index = std::find( vcNumbers.begin(),vcNumbers.end(), number_to_search ); you can check if the index is valid by checking it against vcNumers.end().Something like this. if( vcNumbers.end() != the_index) cout << *it; hopes this helps :)
If u can Dream... U can do it