std :: unordered_map具有自定义值类型,operator [] [英] std::unordered_map with custom value type, operator[]

查看:164
本文介绍了std :: unordered_map具有自定义值类型,operator []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用std :: unordered_map,如示例中所示

I'm trying to use std::unordered_map, as shown in the example here.

class CSVRecord {
public:
    CSVRecord(string csvLine) : _fields(vector<string>()) {...}
    vector<string> _fields; 
};

int main(int argc, char* argv[]) {
    unordered_map<string, CSVRecord> m;
    CSVRecord rec = CSVRecord("test");
    m["t"] = rec;
    return 0;
}

但是, m [t] = rec 提供错误无法调用'CSVRecord的匹配函数:: CSVRecord()'

我使用 m.insert(pair< string,CSVRecord>

I used m.insert(pair<string, CSVRecord>("t",rec)) instead, but I wonder why the original didn't work.

推荐答案

操作符[] 如何工作?

operator [] 搜索提供给它的键,如果元素在map中已经存在,到该元素。如果元素不存在,那么它将键添加到默认构造的对象。在你的情况下,它不能找到合适的构造函数,因此发射错误。

operator[] searches for the key provided to it and if element is already there in map it returns the reference to that element. If element is not there then it adds the key with default constructed object. In your case it was not able to find appropriate constructor hence emitted error.

这篇关于std :: unordered_map具有自定义值类型,operator []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆