相关疑难解决方法(0)

如何创建一个C++映射容器,其中键是值的一部分?

我想存储一堆键值对象,但值对象本身(及其对它的引用)知道它的键.我还想在只给出密钥的情况下有效地查找这些对象.

class SomeObject
{
private:
    //String or integer. int seem cheap enough to duplicate with std::map, but
    //strings seem pretty expensive when there may be thousands of objects in existence.
    //Reference/Pointer to key is fine
    const SomeOtherObject key;
    ...other stuff...
public:
    ...methods, some of which use the key in some way...
};
Run Code Online (Sandbox Code Playgroud)
  • 的std ::地图
    • 似乎要求存储是std :: pair,这样值就无法访问密钥.如果值包含密钥,则需要重复该密钥.
    • 实际上并不强制执行值内部的键不会以某种方式更改
  • 的std ::设为
    • 看起来是一个非常好的解决方案,使用自定义比较方法按键提供唯一性,直到您意识到它使您的整个值成为常量,而不仅仅是关键字段.
  • std :: vector(或其他数组/列表之类的解决方案)
    • 可以使用线性搜索,或者如果项目保持排序二进制搜索.但是我怀疑这在性能方面并不是最优的,并且需要额外的某种层才能真正实现所需的行为.

c++ containers dictionary stl

13
推荐指数
2
解决办法
3309
查看次数

用于STL映射的自定义内存分配器

这个问题是关于在插入std :: map期间构造自定义分配器的实例.

这是一个自定义分配器std::map<int,int>以及使用它的小程序:

#include <stddef.h>
#include <stdio.h>
#include <map>
#include <typeinfo>

class MyPool {
public:
  void * GetNext() {
    return malloc(24);
  }
  void Free(void *ptr) {
    free(ptr);
  }
};

template<typename T>
class MyPoolAlloc {
public:
  static MyPool *pMyPool;

  typedef size_t     size_type;
  typedef ptrdiff_t  difference_type;
  typedef T*         pointer;
  typedef const T*   const_pointer;
  typedef T&         reference;
  typedef const T&   const_reference;
  typedef T          value_type;

  template<typename X>
  struct rebind
  { typedef MyPoolAlloc<X> other; };

  MyPoolAlloc() throw() {
    printf("-------Alloc--CONSTRUCTOR--------%08x %32s\n", this, typeid(T).name()); …
Run Code Online (Sandbox Code Playgroud)

c++ memory-management stl map

11
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×2

stl ×2

containers ×1

dictionary ×1

map ×1

memory-management ×1