[英]std::unordered_map with custom value type, operator[]
I'm trying to use std::unordered_map, as shown in the example here . 我正在尝试使用std :: unordered_map,如此处的示例所示。
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()'
. 但是, m["t"] = rec
给出错误 : 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. 我改用了m.insert(pair<string, CSVRecord>("t",rec))
,但是我不知道为什么原始的行不通。
You are getting this error because of lack of default constructor in your CSVRecord. 由于CSVRecord中缺少默认构造函数,因此出现此错误。
How does operator[]
work? operator[]
如何工作?
operator[]
searches for the key provided to it and if element is already there in map it returns the reference to that element. operator[]
搜索提供给它的键,如果map中已经有元素,它将返回对该元素的引用。 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. 在您的情况下,它找不到合适的构造函数,因此发出了错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.