From Python to c++
nnorwitz at gmail.com
nnorwitz at gmail.com
Wed Mar 22 02:11:24 EST 2006
Marco Aschwanden wrote:
> This is actually a c++ problem. Got no satisfying answer on comp.lang.c++.
> Maybe you can help better because I know, there are many c++-converts ;).
>
> Suppose you've got the following list (first line has field names, second
> line has types and any row after is data):
>
> csv = "name,age,place\nstring,int,string\nMac,25,Zurich\nMike,55,Oslo"
>
> and you would like to turn it into a dictionary:
>
> parsed = {
> "name":["Mac", "Mike"],
> "age":[25, 55],
> "place":["Zurich", "Oslo"]
> }
>
> A trivial task in Python. In C++ it is cumbersome. I was thinking to put
> the parsed data into a map:
>
> map<string, vector<???> >
>
> I have no problem with the key (string) but the value (vector) needs to be
> of varying type. I think C++-STL does not allow what I want.
This is so scary, I probably shouldn't post this. It sounds from your
description, you really want RTTI. I haven't done this in a long
while, so I'm not sure there is an easier way. But the program below
works and seems like it may be what you are asking for.
n
--
#include <stdio.h>
#include <vector>
struct Any {
virtual ~Any() { };
};
typedef std::vector<Any*> List;
class Str : public Any {
public:
Str(const char *s) : value_(s) {};
operator const char*() const {
return value_;
}
private:
const char *value_;
};
class Int : public Any {
public:
Int(int s) : value_(s) {};
operator int() const {
return value_;
}
private:
int value_;
};
int main(int argc, char **argv) {
Str anyone = "someone";
Int my_age = 5;
List list;
list.push_back(&anyone);
list.push_back(&my_age);
for (List::const_iterator i = list.begin(); i != list.end();
i++) {
const Int *iptr;
const Str *str;
if ((str = dynamic_cast<const Str*>(*i)))
printf("string: %s\n", (const char*) *str);
else if ((iptr = dynamic_cast<const Int*>(*i)))
printf("int: %d\n", (int) *iptr);
else
printf("clueless: %p\n", *i);
}
return 0;
}
More information about the Python-list
mailing list