假设一些数据结构:
typedef struct {
std::string s;
int i;
} data;
如果我使用该字段data.s
添加实例时作为键data
在类型地图中std::map<std::string&, data>
,字符串是否被复制?由于引用将变得无效而删除地图的元素是否安全?
这些问题的答案也适用于unordered_map
?
EDIT:
这是我当前的解决方案......但是将迭代器添加到地图是丑陋的:
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 开始参考包装器 https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper是标准的一部分。
#include <functional>
std::map<std::reference_wrapper<std::string>, data>
使用升压
您可能想看一下升压参考 http://www.boost.org/doc/libs/release/doc/html/ref.html。它提供了一个包装器,允许在 STL 容器中使用引用,如下所示:
std::map<boost::reference_wrapper<std::string>, data>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)