Re: Initializing std::map Objects
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;
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).
But I also liked David's suggestion. You could even ged rid of the named
TSINFO object in his example by writing
addEntry(tsLUMap,...params...);
addEntry(tsLUMap,...params...);
addEntry(tsLUMap,...params...);
where
void addEntry(shirtLUMap & map, ...params...);
{
TSINFO & tsi = map[tsCode];
tsi.tsCode = tsCode;
tsi.more = more;
...
}
But maybe you should rethink the whole data structure. It does not look
like a smart choice if you want to use it as a database for all
available T-Shirts.