Reputation: 1692
My sincere apologies for such a naive question. I know this is simple. But nothing comes to my mind now.
I am using C++. I'm a bit concerned about efficiency since this is targeted for an embedded hardware with very less processing power and RAM.
I have 2 integer arrays with 50 members local to a function. I need to determine what is the corresponding number in the second array when an element in the first array is specified and vice versa. I have the information that the element provided to me for look-up belongs to which array i.e. array 1 or array 2.
Ex : Array1 => 500 200 1000 300 .....
Array2 => 250 170 500 400 .....
Input 500 , Output will be 250
Input 400 , Output will be 300
input 200 , Output will be 170 and so on
I think an array look-up will be least efficient. Is stl::map the best option or do i have to look for any efficient search algorithms? I would like to know if you have to do this, which option you will be choosing.
Any thoughts?
Upvotes: 0
Views: 602
Reputation: 153
According to me there are 2 ways of doing it both have already been suggested;
put the both arrays in a map as key pair value and traverse map to find the corresponding value or key.
Traverse the array for which the input is there and calculate the index. Get the value for that index int he other array.
I would go for the second solution as it easier. Moreover with only 50 elements in a static array you don't need to worry about performance.
Upvotes: 1
Reputation: 31972
You can use std::map for readability and a little efficiency as well, though in your case efficiency is of small matter
std::map<int,int> mapping;
.... //populate
cout <<mapping[200]; //170
This is only 1 way (Array 1 -> Array 2) though. Im not sure if any easier way to do the other way, but create a second map.
To support reverse lookup, or going from (Array 2 -> Array 1), Reverse map lookup suggests using Boost.Bimap
Upvotes: 4