How to use a chart in C++?

Hi,
In my program, I want to implement a chart that can be looked through by the program.
For example, the left side would be 0-600, and the right side would be corresponding values. Left and right sides would be like pairs.
I want the program to take an input, and search for it through the left side of the chart. If the value is a whole number, I want it to return the corresponding value. If it is a decimal point number (like 56.7), I want it to return the 2 values it is between (so 56 and 57).
Which data structure should I use? Linked list? Hash map?
Any advice on how to do it better?

Thank you!
A hash map, I don't think it is aware of "previous and next" concepts (correct me if I am wrong..?). Its designed to do a key/value lookup.

The easy way to handle this is simple.

vector<int> table; //or double?
for( ... 600)
table[I] = rightsidevalue;

....

use(table[somevalue]);

and the concept you describe is called linear interpolation (it can also be nonlinear). You can get fancy, or you can take the average.

something like

(table[(int)(value)] + table[(int)(value)+1])/2.0

or whatever you plan to do with the 2 values.


it would WORK to use a hash map and look up the values as I did above. But I suspect the hash map will do tons of extra work that you don't need here (figuring out the keys internally and complicated function to do the mapping). If the left side were anything complicated instead of simple 0-N, the hash map quickly becomes the right way to go.

If you don't need any of the vector algorithms, you can even just use a std array.
Last edited on
Hello yuriy14,

My first thought is to use a "std:map" and a "std::pair" defined as:
std::map<int, std::pair<double, double>> variableName;. The header files are "map" and "utility" for the use of "std::pair".

Other parts of the program could deal with a number like 56.7 as you described or after changing the 56.7, you might be able to use "floor" and "ceil" from "cmath" or "math.h", to change the 56.7. Then if you need to you can replace the values in the std::pair.

Hope that helps,

Andy
Topic archived. No new replies allowed.