简体   繁体   English

使用C ++ STL的多维矢量解

[英]Multidimensional vector solution using c++ STL

I Would like to try the below mentioned implementation using C++ STL. 我想尝试使用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 . 例如,基于下面提到的示例输入,预期的输出是:对于东京=>男人= 1,女人= 1,孩子= 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. 解决这种情况的最有效方法是什么,任何其他解决方案都将受到高度赞赏。

Sample Input 样本输入

在此处输入图片说明

Expected Output [ will be filled accordingly, please ignore empty fields] 预期的输出[将被相应地填充,请忽略空白字段]

在此处输入图片说明

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. 如果顺序无关紧要,请使用unordered_map ,如果可以对其排序,请使用有序map ,如果要保持输入顺序,请使用在索引中存储索引的list

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: 如果已知类别仅获得3个可能的值(男人,女人,孩子),而城市不属于先验知识,则可以使用:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM