I'm new to C++, but basically what I want to do is create a C++ class that contains a private static const hash of string => array_ref_of_strings pairs and just dump it to stdout. Is not much to ask is it? I've create 2 examples of code below. This first one is the Perl example. The second one is my inexperienced idea of how it should be done in C++ which is probably full of inefficiencies and other weirdness. It works, but I'm not sure what I'm doing so please advise. I've added comments and questions to the C++ example. One thing I really want to know is how to declare a variable map (hash) variable as NULL and define it later (Test::_getFood() implementation).
-Craig Manley.
============ This the example Perl script containing a Test class. ===============
#!/usr/bin/perl -w
use strict;
# main
my $t = new Test();
$t->Dump();
exit(0);
# Declare the Test class and it's methods.
package Test;
my $static_food;
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
if (!defined($static_food)) {
$static_food = {
'fruit' => ['apples', 'bananas', 'oranges'],
'vegetables' => ['peas', 'carrots']
};
}
my $self = {'_food' => $static_food};
bless($self,$class);
return $self;
}
sub Dump {
my $self = shift;
my $food = $self->{'_food'};
foreach my $key (keys %{$food}) {
print "$key:\n";
my $vals = $food->{$key};
foreach my $val (@{$vals}) {
print "\t" . $val . "\n";
}
}
}
1;
============ This how I ported it to C++. ===============
#include <map>
#include <vector>
#include <iostream>
using namespace std;
typedef map<string, vector<string> > MSVS;
typedef MSVS::iterator IMSVS;
//////// Interface ////////
class Test {
public:
// Contructor.
Test();
// Dumps contents.
void dump();
protected:
// Returns a static 'food' map.
MSVS _getFood();
};
//////// Implementation ////////
// Contructor.
Test::Test() {
}
// Dumps contents.
void Test::dump() {
MSVS food = this->_getFood(); // Is this assignment efficient (i.e. just a pointer copy)?
for (IMSVS iter = food.begin(); iter != food.end(); iter++) {
cout << iter->first << ":\n";
vector<string> values = iter->second; // Is this assignment efficient (i.e. just a pointer copy)?
for (int i = 0; i < values.size(); i++) {
cout << "\t" << values[i] << "\n";
}
}
}
// Returns a static 'food' map.
MSVS Test::_getFood() {
// Why can't I do this?:
// static MSVS food = NULL;
// if (food == NULL) {
// food = new MSVS();
// ...
// }
//
static bool initialized = false;
static MSVS food;
if (!initialized) {
food["fruit"].push_back("a
pples");
food["fruit"].push_back("b
ananas");
food["fruit"].push_back("o
ranges");
food["vegetables"].push_ba
ck("peas")
;
food["vegetables"].push_ba
ck("carrot
s");
initialized = true;
}
return food;
}
//////// Run it... ////////
int main() {
Test* t = new Test();
t->dump();
return 0;
}
Start Free Trial