开发者

Reverse map a functional relation(c++)

I am using a simple function (y(x)), and I want to generate an x value from a certain y value. While typically reverse mapping does not give a single x value, I am using the maximum from my y values. This means that there will be a unique x value for the y value I input(the ma开发者_JAVA技巧ximum). I don't understand how to code this in c++


If you don't need interpolation, only exact reverse lookup, then it's relatively straighforward:

std::map<YType, XType> lookup;
// (code to read the file goes here)
// for each x {
    YType y = f(x);
    if ((lookup.count(y) == 0) || (lookup[y] < x)) {
        lookup[y] = x;
    }
// }

Then your reverse lookup is just lookup[y], which will return 0 (or a default-constructed value where applicable) if y in fact was missing from the data.

Be aware that my code is a bit inefficient, it looks up y several times in the map, up to 3. You can optimize using iterators, but I'm concerned that obscures what's going on if you're not already familiar with them:

typedef std::map<YType, XType> maptype;
typedef std::pair<maptype::iterator, bool> resulttype;

resulttype result = lookup.insert(std::make_pair(y, x));
if (!result.second) {
    // key already existed, so value was not inserted. Check for max.
    maptype::iterator pos = result.first;
    if ((*pos).second < x) {
        (*pos).second = x;
    }
}


If I understand correctly, you are given a finite range of values x, say x[0], x[1], ..., x[N], and a function f, and you want to find the index k for which f(x[k]) is the largest possible. In that case, a simple search will do:

size_t k = 0;
T m = f(x[k]);
T tmp;

for (size_t i = 1; i <= N; ++i)
{
  if ((tmp = f(x[i])) > m)
  {
    k = i;
    m = tmp;
  }
}

// Maximum is (x[k], m)

Here T is the type such that f is T f(T);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜