rectangletangle rectangletangle - 1 year ago 38
C++ Question

How do I find a particular value in an array and return its index?

Pseudo Code:

int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x;

x = find(3).arr ;

x would then return 2.

Answer Source

The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?).

To find the index, use std::distance and std::find from the <algorithm> header.

int x = std::distance(arr, std::find(arr, arr + 5, 3));

Or you can make it into a more generic function:

template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
    size_t i = 0;
    while (first != last && *first != x)
      ++first, ++i;
    return i;

Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.

In your case, you would use it like so:

size_t x = index_of(arr, arr + 5, 3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download