本文介绍了引用作为std :: map中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一些数据结构:

typedef struct {
    std::string s;
    int i;
} data;

如果在类型为std::map<std::string&, data>的映射中添加data的实例时使用字段data.s作为键,是否会复制字符串?因为参考将无效,所以删除地图的元素是否安全?

If I use the field data.s as key when adding instances of data in a map of type std::map<std::string&, data>, do the string gets copied? Is it safe to erase an element of the map because the reference will become invalid?

这些问题的答案也适用于unordered_map吗?

Also do the answers to these questions also apply to an unordered_map?

这是我当前的解决方案...但是将迭代器添加到地图是很困难的:

This is my current solution... but adding iterator to the map is UGLY:

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;
}

推荐答案

您不能在标准库容器中存储引用-您的地图应如下所示:

You can't store references in Standard Library containers - your map should look like:

map <string,data> mymap;

映射将为您管理密钥字符串和struct实例,它们将是副本. mapunordered_map在这方面的工作方式相同,所有其他标准库容器也是如此.

The map will manage both the key string and the struct instances, which will be copies, for you. Both map and unordered_map work in the same way in this regard, as do all other Standard Library containers.

请注意,在C ++中,不需要typedef来声明结构:

Note that in C++, you don't need typedefs to declare structs:

struct data {
    std::string s;
    int i;
};

这篇关于引用作为std :: map中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:30