c++ - 如果该结构的另一个成员已知,则修改 vector 中的结构成员

标签 c++ vector struct

免责声明:我尝试过一般在线搜索和此处专门搜索。如果这个问题已经得到回答,请重定向我并关闭这个问题。

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

#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,我正在一个 vector 中搜索一个特定的 person 结构将此名称作为 name 成员并更改其 received 成员。

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

最佳答案

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.
}

关于c++ - 如果该结构的另一个成员已知,则修改 vector 中的结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26541198/

相关文章:

C# - 如何在包含数组的结构中编码(marshal)非托管结构

c - 使用 mmap() 如何创建动态大小的结构

c++ - 将公式的结果链接到用户输入并验证它们是否匹配

c++ - 在 C++ 中压缩代码时遇到问题 - SFML

c++ - 数组类 - 获取最大和最小值

c++ - 从 ‘SymbolInfo*’ 转换为 ‘YYSTYPE {aka int}’ 失去精度

r - 在 R 中有效地创建向量的困惑

r - 如何仅保留向量中每个字符串中的唯一单词

matrix - 如何用sympy通过向量乘法执行矩阵?

c++ - 如何在 C++ 中制作可调试文件范围(静态?)类?