繁体   English   中英

如何将列拆分为不同的向量

[英]How can I split columns into a different vector

所以这些数字有 2 列:

1 10
2 -3
3 6
3 -6
1 -5

(数据取自.txt) 第一列是客户数量,第二列是余额 我需要这样操作。 “对于第一个客户余额等于 10-5” “对于第二个客户客户余额等于 -3”。 如果我知道如何将帐户更改为向量,我如何将列拆分为不同的向量,这应该很好。 我知道在 Python 中它看起来像这样:

n = int(input())
account = [0]*100

for i in range(n)
    person, balance = input().split()
    person = int(person)
    balance = int(balance)
    account[person-1] += balance

for x in range(len(account)):
    if account[x] != 0:
        print(x+1, account[x]

但我在 c++ 中需要它。 在这一点上我有这样的事情。 它应该检查有多少个帐户并且只显示 3 个结果。

ifstream file2("number.txt");

    vector<int> number;

    int input2;
    while(file2 >> input2)
    {
        number.push_back(input2);
    }

    int person=0,balance=0;
    int account[5];
    for (int i=0; i<number.size(); i+=2)
    {
        person=number[i];
        balance=number[i+1];
        account[person]+= balance;
    }
    for(int i=1; i<6; i++)
    {
        if(account[i]!=0)
        {
            cout << account[i] << endl;
        }
    }

通常,并行数组表示使用struct的数组(向量):

struct Client
{
    int id;
    double balance;
};

下一步可能是重载operator>>以读取Client实例:

struct Client
{
    int id;
    double balance;
    friend std::istream& operator>>(std::istream& input, Client& c);
};

std::istream& operator>>(std::istream& input, Client& c)
{
    input >> id;
    input >> balance;
    return input;
}

输入数据库

std::vector<Client> database;
Client c;
while (input_file >> c)
{
    database.push_back(c);
}

您可以执行余额为 -5 的搜索操作。
由于浮点数不是精确表示,我们会说如果差值小于 1.0E-5,则数字是精确的。

for (int i = 0; i < database.size(); ++i)
{
   double diff = abs(-5 - database[i].balance);
   if (diff < 1.0E-5)
   {
        break;
   }
}
if (i < database.size())
{
    std::cout << "Client " << database[i].id
              << ", balance: " << database[i].balance
              << "\n";
}

如果您确定对于n客户,所有客户 ID 都尊重0 <= ID <= n

  • 您可以只使用矢量account来存储您的数据,其中客户i余额存储在account[i]
ifstream file2("number.txt");
    vector<int> account;
    int person, balance;
    
    while (file2 >> person >> balance)
    {
        while (account.size() <= person) //making room for new client data 
            account.push_back(0);
        account[person] += balance; //saving client data
    }

    
    for (int i = 1; i < account.size(); i++)
        if (account[i] != 0)
            cout << account[i] << endl;

否则:

  • 您可以使用unordered_map来存储客户端数据
ifstream file2("number.txt");
    unordered_map<int,int> account;
    int person, balance;

    while (file2 >> person >> balance) {
        account[person] += balance;
    }

    for (auto& e : account)
        cout << e.first << " " << e.second << endl;

暂无
暂无

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

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