-1

我正在尝试找到一种方法来使用结构化绑定更改自定义结构的值。我能够做到这一点。我从结构化绑定std::map中引用了一些材料

在下面的代码中,我能够更改 map 的值。我想将unsigned salary默认值 1000 更改为 10000

#include<iostream>
#include<string>
#include<vector>
#include<map>

struct employee {
    unsigned id;
    int roll;
    std::string name;
    std::string role;
    unsigned salary=1000;
};
int main()
{
   std::map<std::string, int> animal_population {
        {"humans", 10},
        {"chickens", 11},
        {"camels", 12},
        {"sheep", 13},
    };
    std::cout<<"Before the change"<<'\n';
    for (const auto &[species, count] : animal_population)
    {
        std::cout << "There are " << count << " " << species
        << " on this planet.\n";
    }
    for (const auto &[species, count] : animal_population)
     {
        if (species=="humans")
        {
            animal_population[species]=2000;
        }

     }
     std::cout<<"After the change"<<'\n';
     for (const auto &[species, count] : animal_population)
     {
            std::cout << "There are " << count << " " << species
            << " on this planet.\n";
     }

    std::vector<employee> employees(4);
    employees[0].id = 1;
    employees[0].name = "hari";
    employees[1].id = 2;
    employees[1].name = "om";


    for (const auto &[id,roll,name,role,salary] : employees) {
        std::cout << "Name: " << name<<'\n'
        << "Role: " << role<<'\n'
        << "Salary: " << salary << '\n';
    }

}

输出

Before the change
There are 12 camels on this planet.
There are 11 chickens on this planet.
There are 10 humans on this planet.
There are 13 sheep on this planet.
After the change
There are 12 camels on this planet.
There are 11 chickens on this planet.
There are 2000 humans on this planet.
There are 13 sheep on this planet.
Name: hari
Role: 
Salary: 1000
Name: om
Role: 
Salary: 1000
Name: 
Role: 
Salary: 1000
Name: 
Role: 
Salary: 1000

改变我试图得到预期的输出

我得到的错误

无法使用 const 限定类型“const int”分配给变量“salary”

for (const auto &[id,roll,name,role,salary] : employees) {
    //employees[].salary = 10000; //not working
    // salary = 10000;            //not working
    std::cout << "Name: " << name<<'\n'
    << "Role: " << role<<'\n'
    << "Salary: " << salary << '\n';
}

预期产出

Before the change
There are 12 camels on this planet.
There are 11 chickens on this planet.
There are 10 humans on this planet.
There are 13 sheep on this planet.
After the change
There are 12 camels on this planet.
There are 11 chickens on this planet.
There are 2000 humans on this planet.
There are 13 sheep on this planet.
Name: hari
Role: 
Salary: 10000
Name: om
Role: 
Salary: 10000
Name: 
Role: 
Salary: 10000
Name: 
Role: 
Salary: 10000

提前感谢您的任何解决方案和建议

4

1 回答 1

2

问题是您的值有constcvalifier。它们是不可修改的。

删除const并使用引用&,以便您可以修改这些变量。

for (auto &[id,roll,name,role,salary] : employees) {
    salary = 10000;
    std::cout << "Name: " << name<<'\n'
    << "Role: " << role<<'\n'
    << "Salary: " << salary << '\n';
}
于 2017-08-21T07:33:59.820 回答