从 C++ 映射中删除一个键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10038985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:31:56  来源:igfitidea点击:

Remove a key from a C++ map

c++map

提问by Steffan Harris

I would like to remove a key from a STL map. However, map.erase()doesn't do anything. How would I go about doing this

我想从 STL 映射中删除一个键。然而, map.erase()什么都不做。我将如何去做这件事

回答by paxdiablo

It depends entirely on how you're calling it but it sounds like you may be using the first,lastoption. If you are, you need to keep in mind that it erase elements starting at first, up to but excludinglast. Provided you follow that rule, iterator-based removal should work fine, either as a single element or a range.

这完全取决于您如何调用它,但听起来您可能正在使用该first,last选项。如果是,则需要记住它会擦除从 开始first到但不包括 的元素last。如果您遵循该规则,基于迭代器的删除应该可以正常工作,无论是作为单个元素还是作为一个范围。

If you're erasing by key, then it should also work, assuming the key is in there of course.

如果您通过密钥擦除,那么它也应该可以工作,当然假设密钥在那里。

The following sample code shows all three methods in action:

以下示例代码显示了所有三种操作方法:

#include <iostream>
#include <map>

int main (void) {
    std::map<char,char> mymap;
    std::map<char,char>::iterator it;

    mymap['a'] = 'A'; mymap['b'] = 'B'; mymap['c'] = 'C';
    mymap['d'] = 'D'; mymap['e'] = 'E'; mymap['f'] = 'F';
    mymap['g'] = 'G'; mymap['h'] = 'H'; mymap['i'] = 'I';

    it = mymap.find ('b');             // by iterator (b), leaves acdefghi.
    mymap.erase (it);

    it = mymap.find ('e');             // by range (e-i), leaves acd.
    mymap.erase (it, mymap.end());

    mymap.erase ('a');                 // by key (a), leaves cd.

    mymap.erase ('z');                 // invalid key (none), leaves cd.

    for (it = mymap.begin(); it != mymap.end(); it++)
        std::cout << (*it).first << " => " << (*it).second << '\n';

    return 0;
}

which outputs:

输出:

c => C
d => D

回答by bobobobo

You would have to find the iteratorfirst

你将不得不找到迭代器第一

map.erase( ITERATOR ) ;

To make this safe, you need to make sure that ITERATOR exists, however. Par example:

但是,为了确保安全,您需要确保 ITERATOR 存在。标准示例:

#include <stdio.h>
#include <map>
using namespace std ;

int main()
{
  map<int,int> m ;
  m.insert( make_pair( 1,1 ) ) ;
  map<int,int>::iterator iter = m.find(1) ;
  if( iter != m.end() )
    m.erase( iter );
  else puts( "not found" ) ;

}