我需要知道对 map 进行就地修改的最佳方法,而不是获取修改后的值的本地拷贝,然后将其再次插入原始 map 。
我在下面详细说明了问题的片段:
#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;
}
对于更复杂的修改,您可以通过引用获取值:
EmployeeDetail& det = iter->second;
det.salary = 1000;
在 C++ 中,您通常不能在迭代时修改集合,但这仅意味着您不能删除/添加项目。在 C++11 中修改现有项通常没问题。您不能修改的是 map
中的键和 set
中元素的任何部分,但它们在 c++ 中是 const
无论如何,11,所以你不能修改那些。在 C++03 中,您需要记住不要更改 set
中元素的关键部分。
关于c++ - 我想在迭代时对 std::map 执行就地修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9196028/