c++ - 引用作为 std::map 中的键

标签 c++ map reference

假设一些数据结构:

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/

相关文章:

c++ - 如何提取以 midi 文件格式播放的所有乐器?

c++ - STL Vector比较问题

javascript - 在 JQVmap 中使用自定义区域

visual-studio - 项目引用与文件引用?

Java - 这两个对象如何相互相等?

c++ - LNK2038 : mismatch detected for 'RuntimeLibrary' with cuda

c++ - 这段代码中对 std::map::operator[] 的调用在哪里?

map - Clojure Maps,键值创建顺序

类和实例变量的 Python 引用

c++ - 将 ASCII 数字字符转换为实际字符