std::unordered_map with custom value type, operator[]

自作多情 提交于 2020-01-05 08:06:46

问题


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

However, m["t"] = rec gives an error: no matching function for call to ‘CSVRecord::CSVRecord()’.

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


回答1:


You are getting this error because of lack of default constructor in your CSVRecord.

How does operator[] work?

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.



来源:https://stackoverflow.com/questions/26800298/stdunordered-map-with-custom-value-type-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!