Re: Initializing std::map Objects
On Monday, 24 June 2013 08:15:10 UTC+1, SG wrote:
Am 23.06.2013 19:57, schrieb Mike Copeland:
I have the following structure and declarations, and I'm looking for
any simple way to initialize a set of default values.
struct TSINFO
{
string tsDescr; // T-Shirt name
string tsValue; // source T-Shirt value
char tsCode; // T-Shirt code (cShirt)
char tsGender; // T-Shirt gender version
int tsCount; // count of T-Shirts of this type
} extern tsWork;
Just a nit, but IIRC, C has deprecated putting the storage class
anywhere but as the first token in the declaration. This would
be a lot cleaner if you defined the class first, then declared
the variable. (But why do you need the variable to begin with?)
And as Ian pointed out, class names really shouldn't be all
caps.
typedef map<char, TSINFO> shirtLUMap;
shirtLUMap tsLUMap;
shirtLUMap::iterator tsluIter; // lookup iterator
That is, I wish to create, say, 5 objects with specific values and
store them into the map. For example,
tsWork.tsCode = 'S';
tsWork.tsGender = 'U';
tsWork.tsCount = 0;
tsWork.tsValue = "";
tsWork.tsDescr = "Small";
shirtLUMap['S'] = tsWork;
tsWork.tsCode = 'M';
tsWork.tsGender = 'U';
tsWork.tsCount = 0;
tsWork.tsValue = "";
tsWork.tsDescr = "Medium";
shirtLUMap['M'] = tsWork;
tsWork.tsCode = 'A';
tsWork.tsGender = 'F';
tsWork.tsCount = 0;
tsWork.tsValue = "";
tsWork.tsDescr = "Female X-Small";
shirtLUMap['A'] = tsWork;
[etc.]
Such code is tedious, and I'd like to learn some way to "shorthand"
the process of declaring certain default values. Using a non-default
constructor seems useful, but I don't know how I'd do it here... Please
advise.. TIA
Try this:
shirtLUMap tsLUMap = {
{'S', {"Small" ,"",'S','U',0}},
{'M', {"Medium","",'M','U',0}},
{'A', {"Female X-Small","",'A','F',0}}
};
in C++11 mode (untested).
Without C++11, you can still copy a statically initialized
C style vector into the map:
struct MapInit
{
char key;
TSINFO value;
operator shirtLUMap::value_type() const
{
return shirtLUMap::value_type( key, value );
}
};
static MapInit init[] =
{
{'S', {"Small" ,"",'S','U',0}},
{'M', {"Medium","",'M','U',0}},
{'A', {"Female X-Small","",'A','F',0}},
};
shirtLUMap theMap( begin( init ), end( init ) );
--
James