0

因此,我将水果名称和相应数量的数据存储在 typedef 结构数组中overallfruit[].nameoverallfruit[].quantity并且我知道我有一定数量的数组NUM

我将如何使用std::map<>来聚合数据,即将任何具有相同名称的水果组合到一个地方并将它们的数量加在一起?

例如存储在数组中

{apple 5
pear 2
grape 6
mangoes 3
apple 2
mangoes 9}

所以我得到

{apple 7
pear 2
grape 6
mangoes 12}
4

4 回答 4

3

保留顺序的微妙问题是其他人忽略的。

我提出了三种方法:


1.创建一个新容器

如果您想保留订单,您可以使用“合并”功能,例如

住在科利鲁

vector<entry> consolidate(vector<entry> const& in)
{
    vector<entry> result;

    for (auto& e : in)
    {
        auto found = find_if(begin(result), end(result), [&e](entry const& a) { return a.name == e.name; });
        if (end(result) == found)
            result.push_back(e);
        else
            found->quantity += e.quantity;
    }

    return result;
}

2.就地合并算法:

住在科利鲁

void consolidate(vector<entry>& data)
{
    auto f = data.begin(), l = data.end();
    while (f!=l)
    {
        auto match = find_if(begin(data), f, [&](entry const& a) { return a.name == f->name; });
        if (match != f)
        {
            match->quantity += f->quantity;
            f = data.erase(f);
            l = data.end();
        } else
        {
            f++;
        }
    }
}

3.使用map

如果您不介意更改顺序,请使用其他答案中建议的地图:

住在科利鲁

#include <map>
#include <string>
#include <iostream>

using namespace std;

struct entry {
    string name;
    unsigned quantity;
};

int main()
{
    const entry array[] = {
        { "apple", 5 },
        { "pear",  2 },
        { "grape", 6 },
        { "mango", 3 },
        { "apple", 2 },
        { "mango", 9 },
    };

    map<string, unsigned> m;
    for (auto& e : array)
        m[e.name] += e.quantity;

    for (auto& e : m)
        cout << e.first << " " << e.second << "\n";
}
于 2013-09-24T08:35:08.820 回答
2

首先使用std::string键(名称)和int数据(数量)创建地图。然后遍历数组,并为每个条目将数量添加到按名称索引的映射中。

于 2013-09-24T08:26:14.237 回答
-1

使用 std::map 索引必须是唯一的,如果您尝试插入多对,它什么也不做。

对于您的问题,这样的事情应该有效:

std::map<string, int> fruits;
for(int i = 0; i<arraylenth; ++i) {
    fruits[overallfruit[i].name] += overallfruit[i].quantity; // add quantity to previous quantity if exists, or insert new map entry
}
于 2013-09-24T08:28:49.353 回答
-2

我可能不明白你的问题,但我看到的是这样的:

std::map<std::string, unsigned int> fruitsMap;
for(std::size_t i = 0 ; i < NUM ; ++i) {
    std::map<std::string, unsigned int>::iterator it = fruitsMap.find(overallfruit[i].name);
    if(it == fruitsMap.end())
        fruitsMap[overallfruit[i].name] = overallfruit[i].quantity;
    else
        vIt->second += overallfruit[i].quantity;
}

它将遍历您的数组并根据您的需要填充地图。

于 2013-09-24T08:30:39.743 回答