Re: Using STL(map) inside of C data structure. How?
Andrew Trapani wrote:
Sorry, but I can't figure out what you want to do here.
I'll take a guess.
#include <map>
#include anything else necessary
typedef struct {
std::map<const char*, int> m;
} sType;
The usual way to do this in C++ is
struct sType {
std::map<const char*, int> m;
};
(But as was recently pointed out in comp.lang.c++ it's not always the
right way
http://groups.google.com/group/comp.lang.c++/msg/fc0d62b1f7683a60?hl=en&)
Or even better typedef the map
struct sType {
// better pick a better name than Map
typedef std::map<const char *, int> Map;
Map m;
};
Also, the usual thing is not to make a char* your map key, but
std::string, like: std::map<std::string,int>. char* can be used, but why?
int main(int argc, char **argv) {
numberOfStructs = 5;
I'm pretty sure you meant:
const size_t numberOfStructs = 5;
But I'm not sure what you're using it for.
sType s = (sType*) malloc(sizeof(sType) * numberOfStructs);
I'm not sure what you wanted here. Can your compiler compile this? Do
you want to make a map with 5 entries? Why then, all the pointer values
for your keys would have to be unique.
s.m.empty(); /* seg faults here */
empty() is just going to tell you if there's any data in the map. I'll
take a truly wild guess that somehow you got some illegal data into your
instance of sType and then the call to empty does something bad.
Did you mean clear()? In that case you'll have to worry a little bit
about who owns the data that your key_type is pointing to.
}
Is this possible? Thanks.
Maybe. I'm not certain of what you want to do. Maybe this might be a
little bit, although not altogether, better.
struct sType {
typedef std::map<std::string, int> Map;
Map m;
};
int main() {
// if we're using std::string, then the key_values
// have to be unique.
static const sType::Map::value_type x[] = {
std::make_pair("a",1),
std::make_pair("b",2),
std::make_pair("c",3),
// etc
};
// a little bit ugly
sType s = { sType::Map(x, x+sizeof(x)/sizeof(x[0])) };
}
I can't get your code to compile. Perhaps you could post something that
can compile and then it might be easier to answer your question.
LR
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]