Home > Software design >  Inserting into vector of maps
Inserting into vector of maps

Time:10-13

I have a vector of maps:

vector<map<string, double>> Fields;

and I'd like to insert elements in a function:

void insert(const string& fieldName, const double& fieldValue) {
    Fields.insert(pair<string, int>(fieldName, fieldValue));
}

But it doesn't find the insert. Any suggestions what would be the correct way of doing it?

CodePudding user response:

This seems to work:

void insert(const string& fieldName, const double& fieldValue) {

    map <string, double> Field;
    Field.insert(pair<string, double>(fieldName, fieldValue));

    Fields.push_back(Field);

CodePudding user response:

By the looks of it, you'd like to create a new map<string,double> every time insert is called:

void insert(const std::string& fieldName, const double& fieldValue) {
    Fields.emplace_back(std::map<std::string,double>{{fieldName, fieldValue}});
}

If you instead what to use fieldName as Key in a map, then you shouldn't put maps in a vector since you then have to search the vector for the map with that Key which is expensive.

An alternative that'll give you fast lookups:

std::map<std::string, double> Fields;

void insert(const std::string& fieldName, const double& fieldValue) {
    Fields[fieldName] = fieldValue;
}
  • Related