C :如何计算数组中唯一客户端的数量并输出其支出

C++: How to count the numbers of unique clients in array and output their spending?

本文关键字:客户端 输出 唯一 何计算 数组 计算      更新时间:2023-10-16

如果我有两个数组,一个存储客户名称,另一个存储他们所花费的数量,我该如何分别输出他们的个人支出?

例如,

array1:[彼得,玛丽,彼得,梅,爱德华]array2:[300,400,500,300,400,500]

所花费的钱的位置与名称相对应,每个人都花了阳性的钱。

我知道数组的大小,但是如何输出他们的个人支出并计算客户次数?

由于客户端可能在数组中具有多个记录,因此我对如何分别计数数字和输出感到有些困惑。

预期:

**支出:**彼得:600玛丽:400......**人数**:4

这是我以前的想法(很抱歉忘记将其包含在我的原始问题中(:

int Array_amount_store[5]; //For storing each clients' amount
for (int i=0; i<=5; i=i+1)  // Initializing
  Array_amount_store[i]=0;
for (int i=0; i<=5; i=i+1)
 for (int j=0; j<=5; j=j+1)
   if (Array1[j]==Array1[i])
      Array_amount_store[i]=Array_amount_store[i]+Array2[i];

我刚刚计算了总数,但陷入了如何输出。

请看一下std::mapstd::unordered_map。将客户名称作为其key,其货币总和作为其value。然后,您可以简单地循环浏览每个名称的购买阵列,然后完成后,循环循环以输出结果。例如:

#include <iostream>
#include <map>
#include <iomanip>
std::map<std::string, double> ClientSpending;
for(int i = 0; i < NumberOfArrayElements; ++i)
    ClientSpending[Array1[i]] += Array2[i];
std::cout << "Spendings:" << std::endl;
for (auto &client : ClientSpending)
    std::cout << client.first << ":" << std::put_money(client.second) << std::endl; 
std::cout << std::endl;
std::cout << "Number of people:" << ClientSpending.size() << std::endl;