Arrays

This is generic question but is there a way to get the index of an array based on the value? I know that if there is an array: int days[4] = {3,5,4,2};
when we int x = day[0]; we know that x = 3. But how can I get the index of a value 3?
iteration. You have to find the value, using whatever technique is appropriate to your program, and when you find the value, that is the index...

a perfect, and reversible, hash function gives you both. This isn't practical for all data, or even most data really.

if the data is an integer of small value, you can do a reverse lookup table.

Beyond that youll need a hash map or other solutions if you want the value fast (near O(1), the forte of arrays).


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
#include <iostream>
#include <string>
using namespace std;

//======================================================================

template<class T> int getIndex( T a[], int size, T valueToFind )
{
   for ( int i = 0; i < size; i++ )
   {
      if ( a[i] == valueToFind ) return i;       // if found, return index
   }
   return -1;                                    // if not found, return an indication of that (-1)
}

//======================================================================

int main()
{
   int iArray[] = { 10, 20, 30, 40 };
   double dArray[] = { 13.4, 15.2, 12.0, -8.7 };
   string sArray[] = { "Vauxhall", "Citroen", "Volkswagen", "Toyota", "Ford", "Volvo" };

   int    ival = 30    ;   cout << "Value: " << ival << "    Index: " << getIndex( iArray, 4, ival ) << endl;
   double dval = 15.2  ;   cout << "Value: " << dval << "    Index: " << getIndex( dArray, 4, dval ) << endl;
   string sval = "Ford";   cout << "Value: " << sval << "    Index: " << getIndex( sArray, 6, sval ) << endl;
          sval = "FFFF";   cout << "Value: " << sval << "    Index: " << getIndex( sArray, 6, sval ) << endl;
}

closed account (48T7M4Gy)
http://stackoverflow.com/questions/25003961/find-array-index-if-given-value
If you know the address of the item then you can find the index with pointer arithmetic, which is much faster:
1
2
3
int days[4] = {3,5,4,2};
int &x = day[0];
size_t indexOfX = &x - days


Also, do you have to use an array? If you're looking up items in a collection by value, an array is not an appropriate data structure.
Thank you for your help! I know that this might not be idea structure to use but Im glad to learn something new
Topic archived. No new replies allowed.