【问题标题】:C++ How do I get a reference to a nested map, to remove an element?C ++如何获取对嵌套映射的引用以删除元素?
【发布时间】:2020-10-18 05:33:34
【问题描述】:

如何在此处获得对第二张地图的参考?我希望能够使用 items.erase() 删除元素。在下面的示例中,主地图中的元素数量不会改变,它只会改变副本。请仅使用 C++ 98。

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

using namespace std;

int main()
{
    map<int, map<int, string> > acks;
    acks[10].insert(make_pair(1, "a"));
    acks[10].insert(make_pair(2, "b"));
    acks[10].insert(make_pair(3, "c"));

    acks[20].insert(make_pair(11, "b"));
    acks[20].insert(make_pair(12, "c"));
    
    map<int, map<int, string> >::const_iterator it = acks.find(10);
    if (it != acks.end())
    {
        map<int, string> items = it->second;
        map<int, string>::const_iterator it2 = items.find(3);
        cout << "size before: " << acks[10].size() << endl;
        items.erase(it2);
        cout << "size after: " << acks[10].size() << endl;
    }
}

【问题讨论】:

    标签: c++ c++98


    【解决方案1】:

    复制发生在这里

     map<int, string> items = it->second;
    

    所以只需将其更改为参考

     map<int, string>& items = it->second;
    

    我想你也需要改变

    map<int, map<int, string> >::const_iterator it = acks.find(10);
    

    map<int, map<int, string> >::iterator it = acks.find(10);
    

    【讨论】:

    • 哦,const_iterator 给我带来了问题。我之前尝试使用指针变量,但遇到了编译器错误。将 const_iterator 更改为 iterator 修复了它。谢谢!
    猜你喜欢
    • 2013-07-25
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多