简体   繁体   English

从 C++ map 中删除密钥

[英]Remove a key from a C++ map

I would like to remove a key from a STL map. However, map.erase() doesn't do anything.我想从 STL map 中删除一个密钥。但是, map.erase()不执行任何操作。 How would I go about doing this我将如何 go 这样做

It depends entirely on how you're calling it but it sounds like you may be using the first,last option.这完全取决于您如何称呼它,但听起来您可能正在使用第first,last选项。 If you are, you need to keep in mind that it erase elements starting at first , up to but excluding last .如果你是,你需要记住它会擦除从first开始的元素,直到但不包括last Provided you follow that rule, iterator-based removal should work fine, either as a single element or a range.如果您遵循该规则,基于迭代器的删除应该可以正常工作,无论是作为单个元素还是作为范围。

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

You would have to find the iterator first你必须先找到迭代器

map.erase( ITERATOR ) ;

To make this safe, you need to make sure that ITERATOR exists, however.但是,为了确保安全,您需要确保 ITERATOR 存在。 Par example:范例:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM