简体   繁体   English

C ++ unordered_map阻止字符串键的内存重新分配

[英]C++ unordered_map prevent memory reallocation for string keys

I am creating an unordered_map (C++ STL). 我正在创建一个unordered_map(C ++ STL)。 The key is of type std::string and the value will be a pointer to objects of class X. the string key is actually the name of the object itself and will be stored as an instance variable in objects of that class. 键的类型为std :: string,值为指向类X的对象的指针。字符串键实际上是对象本身的名称,将作为实例变量存储在该类的对象中。 Is there a way for me to insert key,value pairs in unordered_map so that it does not allocate memory for the key? 我有没有办法在unordered_map中插入键值对,以便它不为键分配内存?

I came up with the following solution -> 我提出了以下解决方案 - >

class X
{
public:
    const string name;
    X(char * c_name) : name(c_name) {}
};

unordered_map<string, X *> x_store;
X *a = new X("some_name"); 
x_store.insert(make_pair(a -> name, a))

but i believe the string object will be duplicated. 但我相信字符串对象将被复制。

You cannot make unordered_map rely on your keys: it must store its own copy, because you could potentially change the string inside your X class. 你不能让unordered_map依赖你的密钥:它必须存储它自己的副本,因为你可能会改变你的X类中的字符串。

However, you do not need to use a map - it looks like an unordered_set would be sufficient in your situation, with some custom equality and hash functions: 但是,您不需要使用映射 - 在您的情况下看起来像unordered_set就足够了,具有一些自定义相等和散列函数:

auto my_hash = [](X const& x) {
    return std::hash<std::string>()(x.name);
};
auto my_eq = [](X const& x, X const& y) {
    return std::equal_to<std::string>()(x.name, y.name);
};
std::unordered_set<X,my_hash,my_eq> mySet;

Now the key information is stored within the X object, which is stored inside mySet . 现在,关键信息存储在X对象中,该对象存储在mySet Of course you cannot query a set by a string key, but you can use find and a "query object" to achieve the same result: 当然,您无法通过字符串键查询集合,但您可以使用find和“查询对象”来实现相同的结果:

X query("abc"); // Set the name to "abc"
X *current = mySet.find(query);
if (current) {
    cout << current->name << endl; // Will print "abc"
} else {
    cout << "Not found" << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM