Reputation: 13
So there are 2 columns of these numbers:
1 10
2 -3
3 6
3 -6
1 -5
(data is taken from .txt) First column is number of client, second is balance I need to do operation like this. "for first client balance is equal to 10-5" "For second client client balance is equal to -3". How I can split columns to different for example vectors if I know how change account to vector this should be good. I know in Python it's gonna look something like this:
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]
But I need it in c++. I have something like this at this point. It should check how many accounts there is and show only 3 results.
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;
}
}
Upvotes: 0
Views: 106
Reputation: 79
if you are sure that for n
clients all the clients ID respect 0 <= ID <= n
:
account
to store your data, where the client i
balance is stored at 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;
Otherwise :
unordered_map
to store the client dataifstream 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;
Upvotes: 0
Reputation: 57729
Often, a parallel array is an indication to use an array (vector) of struct
:
struct Client
{
int id;
double balance;
};
The next step could be to overload operator>>
to read in a Client
instance:
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;
}
To input into a database:
std::vector<Client> database;
Client c;
while (input_file >> c)
{
database.push_back(c);
}
You could do an search operation where the balance is -5.
Since floating point is not exact representation, we'll say that if the difference is less than 1.0E-5 the numbers are exact.
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";
}
Upvotes: 1