const accessor to map?

N

nw

Hi comp.lang.c++,

I'm using map to store a bunch of vectors. I'd like to be able to
return const references to the vectors from my object. However I can't
see a way of doing this with map, as the vectors aren't const. Is
there a way round this, or a better container I should be using?

Advice appreciated.

Example follows:

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

using namespace std;

class MyMapEncap {
public:

map<string,vector<int> > mymap;

const vector<int> &getvec(string id) const { // Doesn't work because
this isn't allow to be const
// I
want to keep it const is there a work around?
return mymap[id];
}
};

int main() {
MyMapEncap e;

e.getvec("RAW");

}
 
N

nw

I figured it out. Basically use find to access the elements:

#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");

}
 
S

Stefan Naewe

I figured it out. Basically use find to access the elements:

#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");

Crash! Boom! Bang!

You need to check the return value of mymap.find() !!

/S
 
H

Harsh Puri

Crash! Boom! Bang!




You need to check the return value of mymap.find() !!

/S
--
Stefan Naewe            stefan dot naewe at atlas-elektronik dot com
Don't top-post  http://www.catb.org/~esr/jargon/html/T/top-post.html
Plain text mails only, please      http://www.expita.com/nomime.html- Hide quoted text -

- Show quoted text -

Yes and probably you should think about passing the vector as a
parameter by reference, rather than returning it from the function.

In the latter you need to worry about what to return if the string id
is not in the map.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,269
Latest member
vinaykumar_nevatia23

Latest Threads

Top