C 索引中的字符串映射而无需分配

C++ index into string map without allocation

本文关键字:分配 映射 字符串 索引      更新时间:2023-10-16

我正在编写一个不允许分配的高性能线程的应用程序。我有一张看起来像这样的地图:

map<String, MyCustomClass> objectCollection;

其中字符串是围绕std :: string的自定义包装器。我希望能够在高优先级线程上写下这样的代码:

int someValue = objectCollection["some string"].value;

执行此操作时,索引到阵列会导致构造字符串,这需要分配。我的想法是,我可能能够为我的地图定义一个可以接受const char*的自定义比较器,并且能够与字符串的C字符串胆量进行字符串比较。这可能吗?看起来如何?

我可以通过字符串实例进行类似的操作:

String strTest = "";
const char* chars = strTest.chars();

您只能进行一个分配。

static const string Key("some string");
int someValue = objectCollection[Key];

以零分配进行操作将需要不同的字符串类。您将以某种方式使用const char*和自定义比较机制。

自定义比较不会对地图有任何好处;无论比较操作员如何工作,查找操作员总是将其参数转换为关键类型。但是,当您想要快速查找时,可能会有更好的方法。

将事物放在分类的矢量中,并使用二进制搜索算法(lower_bound()等)查找它们,通常比在地图中查找它们更快(因为除其他事项外,指针在每个查找上追逐)。映射的插入速度要比排序的向量要快得多,但是当快速查找比快速插入更重要时,矢量通常更快,并且向量具有您可以使用异质比较功能的优势(一个采用两个不同的参数,类型)。

类似的东西:

struct Element {
    std::string key;
    Thing value;
};
bool compare(const Element& lhs, const char* rhs) {
    return lhs.key < rhs;
}
using Collection = std::vector<Element>;
inline Thing lookup(const char* key, const Collection& coll) {
    // Requires coll to be already sorted
    auto i(std::lower_bound(coll.begin(), coll.end(), key, compare));
    if (i != coll.end() && i->key == key)
        return i->value;
    else
        return Thing();
}

在C 14中,有一些整洁的新功能应允许这种情况发生。例如,有一个模板地图:: find

template< class K > iterator find( const K& x );

http://en.cppreference.com/w/cpp/container/map/find

您所能做的就是将key_type更改为const char*,因为map :: find as aid map :: operator [] and map :: at map :: at tik tik key_type作为他们的参数。因此,即使您通过const char*,它将在调用地图函数之前构造字符串。因此,除非您使绳子静态,否则您不会逃脱而不构造一个。