Quote:Original post by random_thinkerA couple of comments:
Hi Again All,
Thanks for the excellent info...still formulating an approach to this...to keep things simple and to play on some of the ideas above, what about something like (this pseudocode has not been tested!):
// Consider each parsed element as an atom that is either number or text.
struct atom
{
double number;
std::string text;
};
// Does the string resemble a number?
bool isNumber(const std::string & strg)
{ return (strg.find_first_not_of(<number_string>) == std::string::npos); }
// Make a new atom from a string at initial parsing.
atom * makeAtom(const std::string & strg)
{
atom * pAtom;
if(isNumber(strg))
{
pAtom->number = lexical_cast<double>(strg);
pAtom->text = "";
}
else
{
pAtom->number = 0;
pAtom->text = strg;
}
return pAtom; // on exit, content is returned and pAtom is destroyed.
}
// Convenience typedefs allowing dynamic allocation.
typedef std::map<std::string,atom*> atom_map;
typedef std::vector<atom_map*> atom_map_vec;
// Create an atom_map_vec.
atom_map_vec = amvec;
// Load first atom_map.
amvec.push_back(new atom_map);
// Parse a key-value string and return them.
std::string key = "string_key";
std::string value = "123.789";
// Insert a key-value pair.
amvec[0]->insert(std::make_pair(key,(makeAtom(value))));
The above should allow some form of dynamic allocation, and when each map pair is used the 'non-null' values only would be accessed. This also preserves type safety and because all containers are iterating across pointers the efficiency should be preserved. However, it still does not seem the best solution to me.
Any suggestions or ideas?
1. In your makeAtom() function, no memory is allocated for pAtom, and the value of pAtom is never initialized. Because of this, the behavior of this function (and any code that uses its return value) will be undefined.
2. The comment 'on exit, content is returned and pAtom is destroyed' is somewhat confusing. What exactly are you expecting to be destroyed at this point? (It is true that pAtom itself is destroyed, but I'm not sure that this is what you mean.)
3. The line 'atom_map_vec = amvec;' should be 'atom_map_vec amvec;', I think.
4. What's the rationale for storing everything (maps, atoms, etc.) by reference (i.e. pointer) rather than by value? (You touched on this in your post, but I wasn't quite clear what you were getting at.)
5. Given what you posted above, it seems that the aforementioned boost::variant would be an appropriate solution to the problem (unless I'm missing something). Have you considered using variant?
[Edit: Some of the programming errors mentioned above - e.g. not allocating memory for pAtom - are probably just because, as you said, it's untested code. I'm still curious about items 4 and 5 though.]