问题
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