C 索引中的字符串映射而无需分配
C++ index into string map without allocation
我正在编写一个不允许分配的高性能线程的应用程序。我有一张看起来像这样的地图:
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*,它将在调用地图函数之前构造字符串。因此,除非您使绳子静态,否则您不会逃脱而不构造一个。
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- C++ 将元素分配给映射值时访问错误
- 包含动态分配内存作为值的映射的取消定位速度有多快?
- 如果可能,标准::映射分配是否静态
- 如何在 OpenCL 中使用缓冲区分配和映射内存机制
- 我如何正确地为std ::映射分配内存
- 我如何将输入分配给在 for 循环中设置的映射功能
- 映射和设置总是一次分配一个项目吗
- 静态映射中动态分配的对象.删除必要的
- C++:通过从映射向量分配映射实例来填充映射的映射
- 映射中的分配最终为0
- C 索引中的字符串映射而无需分配
- 循环访问映射并删除动态分配的元素
- 将无序映射与动态分配的用户定义类一起使用
- STL映射是如何分配的?堆叠或堆
- 任何查找分配给映射的内存大小的方法
- 两个映射之间的分配-移动语义和性能
- 动态分配映射指针值
- 在类成员中创建和分配映射
- 如何使用malloc分配映射键