Reputation: 1506
Disclaimer: I tried searching both online generally and here specifically. If this question has been answered already, please redirect me and close this one.
I have a coding problem and I'm trying to solve it with the following code:
#include <fstream>
#include <map>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream fin("gifts1.in", ios::in);
ofstream fout("gifts1.out", ios::out);
unsigned short NP;
struct person
{
string name;
unsigned int gave;
unsigned int received;
};
vector<person> accounts;
string tmp_name;
person buf_person;
fin >> NP;
accounts.resize(NP);
for (auto i : accounts)
{
fin >> tmp_name;
i.name = tmp_name;
i.gave = i.received = 0;
}
for (auto j : accounts)
{
string name;
fin >> name;
unsigned int sum, people;
fin >> sum >> people;
j.gave = sum;
if (people != 0)
{
for (int i = 1; i < people; i++)
{
string receiver_name;
fin >> receiver_name;
accounts.receiver_name.received = sum / people; // no idea here
}
j.gave -= sum % people; // if a person meant to give 200, but couldn't divide 3,
// he actually gave 197
}
}
fin.close();
fout.close();
exit(0);
}
The inner for
loop is supposed to work like this: I'm given a string receiver_name
, I'm searching in a vector for a particular person
struct that has this name as a name
member and change its received
member.
The question is: is this possible and how do I do it if it is?
Upvotes: 1
Views: 52
Reputation: 52471
vector<person>::iterator it = std::find_if(accounts.begin(), accounts.end(),
[&receiver_name](const person& p) { return p.name == receiver_name; });
if (it == accounts.end()) {
// No person with this name
} else {
person& found = *it;
// Do what you need here.
}
Upvotes: 3