这些数字有两列:
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;
}
}发布于 2021-02-11 22:32:12
如果您确信对于n客户端,所有客户端都尊重0 <= ID <= n
您可以使用向量account[i]来存储数据,其中客户端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;发布于 2021-02-11 22:01:36
通常,并行数组是使用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";
}https://stackoverflow.com/questions/66162898
复制相似问题