假设一些数据结构:
typedef struct {
std::string s;
int i;
} data;
如果我使用字段 data.s
添加 data
的实例时作为键在 std::map<std::string&, data>
类型的 map 中,字符串是否被复制?删除 map 元素是否安全,因为引用将变为无效?
这些问题的答案同样适用于 unordered_map
?
编辑:
这是我目前的解决方案...但是向 map 添加迭代器是丑陋的:
typedef struct {
const std::string* s;
int i;
} data;
std::map<std::string, data> map;
typedef std::map<std::string, data>::iterator iterator;
// add an element to the map
iterator add_element(const std::string& s) {
std::pair<iterator, bool> p = states.insert(std::make_pair(s, data()));
iterator i = p.first;
if(p.second) {
data& d = (*i).second;
d.s = &(*i).first;
}
return i;
}
最佳答案
C++11
C++11 起 reference wrapper是标准的一部分。
#include <functional>
std::map<std::reference_wrapper<std::string>, data>
使用 Boost
您可能想看看 boost.ref .它提供了一个包装器,使引用能够在 STL 容器中使用,如下所示:
std::map<boost::reference_wrapper<std::string>, data>
关于c++ - 引用作为 std::map 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3235927/