我想在迭代它时对std :: map进行就地修改

Sid*_*Sid 5 c++

我需要知道对地图进行原位修改的最佳方法,而不需要修改值的本地副本,然后将其再次推送到原始地图中.

我已经详细介绍了下面解释问题的代码段:

#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)

Nim*_*Nim 6

iter->second是对EmployeeDetail对象的引用,您可以直接修改它 - 例如

   foreach( iter, eMap )  
   {  
       if ( compareByNameAge(name, age, iter->first) )  
       {
           iter->second.salary = 1000;
       }  
   }  
Run Code Online (Sandbox Code Playgroud)

不需要 transformMap

  • @Sid,你并没有真正避免迭代,它只是被一些花哨的语法隐藏了,为什么不保持原样呢?正在发生的事情非常易读(除了您自定义的 `foreach`),在 c++11 中,这变得更加简单 `for(auto it : eMap) { ... }` (2认同)

Gri*_*zly 5

您可以直接通过迭代器(直接指向相应的项)修改元素:

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.


And*_*ron 4

拿个参考值就可以了。

EmployeeDetail& det = iter->second;   // notice new '&' character.
det.salary = 1000;   // modifies the 'EmployeeDetail' object in-place.
Run Code Online (Sandbox Code Playgroud)