简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM