【问题标题】:Modifying a member of a struct in a vector if another member of that struct is known如果该结构的另一个成员已知,则在向量中修改该结构的成员
【发布时间】:2014-10-24 03:51:14
【问题描述】:

免责声明:我尝试在网上和这里专门搜索。如果这个问题已经回答了,请重定向我并关闭这个问题。

我有一个编码问题,我正在尝试使用以下代码解决它:

#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);
}

内部for 循环应该像这样工作:我得到一个string receiver_name,我正在向量中搜索一个特定的person 结构,该结构具有这个名称作为name 成员和更改其received 成员。

问题是:这可能吗?如果可以,我该怎么做?

【问题讨论】:

    标签: c++ vector struct


    【解决方案1】:
    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.
    }
    

    【讨论】:

    • 它看起来既优雅又神秘。另外,请澄清一下:这是一个 lambda 吗?
    • 澄清一下:这段代码确实使用了 lambda。
    • 太棒了。谢谢。我可能需要更多地了解他们。对于可能会找到这段代码的后代:std::find_if&lt;algorithm&gt;
    猜你喜欢
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2021-07-26
    • 2014-06-09
    相关资源
    最近更新 更多