- I want to perform in place modification to a std::map while iterating over it
- #include <string>
- #include <map>
- struct EmployeeKey
- {
- std::string name;
- int amount;
- int age;
- };
- struct EmployeeDetail
- {
- std::string dept;
- int section;
- int salary;
- };
- bool compareByNameAge(const std::string& name,
- const int& age,
- const EmployeeKey& key )
- {
- return name > key.name && age > key.age;
- }
- typedef std::map<EmployeeKey, EmployeeDetail> EmployeeMap;
- int main()
- {
- EmployeeMap eMap;
- // insert entries to the map
- int age = 10;
- std::string name = "John";
- EmployeeMap transformMap;
- foreach( iter, eMap )
- {
- if ( compareByNameAge(name, age, iter->first) )
- {
- //**This is what i want to avoid.......
- // take a copy of the data modified
- // push it in a new map.
- EmployeeDetail det = iter->second;
- det.salary = 1000;
- transformMap[iter->first] = det;
- }
- }
- //** Also, i need to avoid too...
- // do the cpy of the modified values
- // from the transform map to the
- // original map
- foreach( iter1, transformMap )
- eMap[iter1->first] = iter1->second;
- }
- foreach( iter, eMap )
- {
- if ( compareByNameAge(name, age, iter->first) )
- {
- iter->second.salary = 1000;
- }
- }
- foreach(iter, eMap)
- {
- if (compareByNameAge(name, age, iter->first))
- iter->second.salary = 1000;
- }
- EmployeeDetail& det = iter->second;
- det.salary = 1000;
- EmployeeDetail& det = iter->second; // notice new '&' character.
- det.salary = 1000; // modifies the 'EmployeeDetail' object in-place.
- it->second.salary = 1000;
- class SalaryUpdater
- {
- public:
- SalaryUpdater(const std::string& name, int age) : name_(name), age_(age) { }
- void operator()(EmployeeMap::value_type& item)
- {
- if(compareByNameAge(name_, age_, item.first))
- {
- item.second.salary = 1000;
- }
- }
- private:
- std::string name_;
- int age_;
- };
- int main()
- {
- EmployeeMap eMap;
- // insert entries to the map
- std::for_each(eMap.begin(), eMap.end(), SalaryUpdater("John", 10));
- }
- for (auto& pair : eMap )
- if (pair.first.name == "Rob")
- pair.second.salary *= 1000;
- for(EmployeeMap::iterator it = eMap.begin(); it != eMap.end(); ++it)
- if(pair.first.name == "Rob")
- pair.second.hours /= 2;