如何在c ++中找到数组元素的最大值?

时间:2017-01-04 22:07:17

标签: c++ arrays struct

我列出了一系列国家,他们的城市以及居住在这些城市中的人数。我需要找到每个国家人口最少的城市:

给出的数据:

Springfield USA 16876
Xao China 1477555
Getfield UK 812 
Sheffield USA 18600
Joji India 5565
Huffington USA 7891
Saji India 774
Pubfield UK 332 
Ming China 4555
Lao China 502

结果必须是:

Huffington 7891
Lao 502
Pubfield 332
Saji 774

最有效的方法是什么?

2 个答案:

答案 0 :(得分:2)

我会将数据放在矢量中,然后对矢量进行排序

struct City {
    std::string name;
    std::string country;
    int population;
};
std::vector<City> cities;

然后根据人口对它们进行排序:

std::sort(cities.begin(), cities.end(), 
     [](City& a, City& b) { return a.population > b.population; });

然后删除最低的项目。

修改 这是一个不同的版本,可以按国家/地区创建最低人口的矢量。

首先,将sort更改为按国家排序:

std::sort(cities.begin(), cities.end(), 
    [](City& a, City& b) {
        if (a.country == b.country) {
            return a.population < b.population;
        }
        else {
            return a.country.compare(b.country) < 0;
        }
    });

现在,创建一个人口最少的第二个向量:

// Copy
std::vector<City> countries = cities;
// Remove duplicates.
// Note this works in our case because of the way the vector is sorted
auto it = std::unique(countries.begin(), countries.end(),
    [](City& a, City& b) { return a.country == b.country; });
countries.resize(std::distance(countries.begin(), it));

此时,countries向量看起来像这样:

Lao China 502
Saji India 774
Pubfield UK 332
Huffington USA 7891

答案 1 :(得分:0)

如果您事先知道您将拥有哪些国家/地区。

您可以创建“string”和“int”的地图,也可以创建一个城市数组,其大小将与地图的大小相同。

在地图中,“字符串”是国家/地区的名称,“int”是您在一个国家/地区的人数。

然后遍历列表并检查每个项目是否具有最少人数。 并在数组中写下特定城市的名称。