I Would like to try the below mentioned implementation using C++ STL. My requirement is to create a Matrix mentioned below. The string of vectors are :
Basically i would want to update the matrix counting the no of Man/woman/kids. For eg Based on the Sample Input mentioned below ,expected output is: For Tokyo => Man=1, Woman=1, Kid=0 .
The approach I think is to first sort the Cities and get the unique values. and then similarly do it for Man, Woman & Kids. Then count the no of Man/Woman/kids for that city. To do this which kind of container would be ideal, ordered map ? How should i handle such multidimensional array problems. What would be the most efficient way to handle this kind of situation.Any other solution would be highly appreciated.
It depends whether the possible values of any dimensions are know a priori or not. If they are, a simple array will be the best container, else you should use a map. If order does not matter, use an unordered_map
, if you can sort it, use an ordered map
, and if you want to keep input order, use a list
where the indexes are stored in a map.
If the categories are known to get only 3 possible values (Man, Woman, Kid) and the cities are not known a priori, I would use:
std::map<std::string, std::array<int, 3> > resul;
std::string town, cat;
for(;;) {
std::cin >> town >> cat;
if (! std::cin) break;
if (resul.find(town) == resul.end()) {
resul[town].fill(0);
}
std::array<int, 3>& curtown = resul[town];
if (cat == "Man") curtown[MAN] += 1;
else if (cat == "Woman") curtown[WOMAN] += 1;
else curtown[KID] += 1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.