在 C++ 中存储和检索多个键 [英] Storing and retrieving multiple keys in C++

查看:29
本文介绍了在 C++ 中存储和检索多个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个整数键需要检索值.根据键存储和检索值的最有效方法是什么?

I have a few integer keys that is needed to retrieve a value. What is the most efficient way to store and retrieve the value based on the keys?

目前我正在将三个键转换并组合成一个字符串,并将键值对存储在映射中.但是,我认为应该有一种更有效的方法来仅基于整数值来执行此操作,例如基于三个键生成单个键.对此有什么想法吗?

Currently I am converting and combining the three keys into a single string and store the key-value pair in a map. However, I think there should be a more efficient way of doing that based on the integer value alone for example generating a single key based on the three keys. Any ideas on that?

谢谢.

推荐答案

几乎可以肯定,您可以比转换为字符串做得更好(这通常是一个相当慢的操作).如果您的三个项目的范围足够小,您可以进行一些移位和相加,将它们组合成一个范围更大的整数.

You can almost certainly do better than converting to a string (which is generally quite a slow operation). If your three items have small enough ranges, you can do some shifting and adding to put them together into a single integer with a larger range.

如果没有,您可以创建一个包含三个整数的结构,并定义 operator< 以合理的方式比较它们:

Lacking that, you can just create a struct that holds three ints, and defines operator< to compare them in a reasonable fashion:

class key { 
    int a, b, c;
public:
    bool operator<(key const &other) { 
        if (a < other.a)
            return true;
        if (a > other.a)
            return false;
        if (b < other.b)
            return true;
        if (b > other.b)
            return false;
        if (c < other.c)
            return true;
        return false;
    }
};

对于那些关心它的人来说,使用 (std | tr1 | boost)::tuple 不会改变答案的特性,但会消除大部分代码.元组与 std::pair 非常相似,除了它支持任意数量的项目而不是两个.对于上面的示例,您可以使用以下内容:

for those who care about it, using (std | tr1 | boost)::tuple wouldn't change the character of answer much, but would eliminate most of the code. A tuple is pretty similar to std::pair, except that it supports an arbitrary number of items instead of just two. For the example above, you could use something like:

#include <tuple>

namespace stdx = std::tr1;    // or stdx=boost::tr1, etc.

typedef stdx::tuple<int, int, int> key_t;

std::map<key_t, whatever> my_map;

tuple 定义了自动假设类型可比较的比较运算符(即,用于比较具有相同元素数量的两个元组,并且对应元素的类型是可比较的).在这种情况下,它进行字典比较(即,比较的结果是第一对不相等的对应元素的结果——如果不存在这样的元素,则两者比较相等).

tuple defines comparison operators automatically assuming the types are comparable (i.e., for comparing two tuples with the same number of elements, and the types of corresponding elements are comparable). In this case it does a lexicographic comparison (i.e., the result of the comparison is the result from the first pair of corresponding elements that are not equal -- of no such element exists, the two compare equal).

这篇关于在 C++ 中存储和检索多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆