Wednesday, April 23, 2008

map const accessor

I wanted to access map in a const form. However the default [] accessor doesn't allow you to do that, because it will create a new entry in map if the thing you are looking for doesn't exist. This program describes the problem:

#include <iostream>
#include <vector>
#include <map>

using namespace std;

class MyMapEncap {
public:

map<string,vector<int> > mymap;

const vector<int> &getvec(string id) const {
return mymap[id];
}
};

int main() {
MyMapEncap e;

e.getvec("RAW");

}



The solution is to use the find method which returns an iterator to the thing your looking for in the above example like this:

#include <iostream>
#include <vector>
#include <map>

using namespace std;

class MyMapEncap {
public:

map<string,vector<int> > mymap;

const vector<int> &getvec(string id) const {
return (*mymap.find(id)).second;
}
};

int main() {
MyMapEncap e;

e.getvec("RAW");

}



No comments: