我需要知道对地图进行原位修改的最佳方法,而不需要修改值的本地副本,然后将其再次推送到原始地图中.
我已经详细介绍了下面解释问题的代码段:
#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;
}
Run Code Online (Sandbox Code Playgroud)
iter->second是对EmployeeDetail对象的引用,您可以直接修改它 - 例如
foreach( iter, eMap )
{
if ( compareByNameAge(name, age, iter->first) )
{
iter->second.salary = 1000;
}
}
Run Code Online (Sandbox Code Playgroud)
不需要 transformMap
您可以直接通过迭代器(直接指向相应的项)修改元素:
foreach(iter, eMap)
{
if (compareByNameAge(name, age, iter->first))
iter->second.salary = 1000;
}
Run Code Online (Sandbox Code Playgroud)
对于更复杂的修改,您可以通过引用获取值:
EmployeeDetail& det = iter->second;
det.salary = 1000;
Run Code Online (Sandbox Code Playgroud)
在c ++中,您通常不能在迭代时修改集合,但这只意味着您无法删除/添加项目.在C++ 11中修改现有项通常很好.你不能修改的是map元素中a 和任何部分的键set,但是那些都是constc ++ 11中的,所以你不能修改它们.在C++ 03中,您需要记住不要更改元素中的元素的键部分set.
拿个参考值就可以了。
EmployeeDetail& det = iter->second; // notice new '&' character.
det.salary = 1000; // modifies the 'EmployeeDetail' object in-place.
Run Code Online (Sandbox Code Playgroud)