根据键值删除multimap中的元素?

时间:2016-12-16 10:15:30

标签: c++ c++11 dictionary stl

如何删除密钥小于或等于 20 std :: multimap 中的所有元素?

我知道如何擦除,我不知道如何传递条件"键小于20"

2 个答案:

答案 0 :(得分:7)

下一个代码应该有效:

std::multimap<int, int> M;
// initialize M here
auto it = M.upper_bound(20);
M.erase(M.begin(), it);

只需使用upper_bound,然后使用erase

答案 1 :(得分:0)

#include <map>
#include <utility>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
    multimap<int, int> mp;

    mp.insert(make_pair(10, 20));
    mp.insert(make_pair(11, 22));
    mp.insert(make_pair(12, 24));
    mp.insert(make_pair(12, 25));
    mp.insert(make_pair(13, 26));
    mp.insert(make_pair(24, 27));
    mp.insert(make_pair(25, 29));
    mp.insert(make_pair(26, 30));

    for(auto& elem : mp)
        cout<<"  first = "<<elem.first<<"  second = "<<elem.second<<endl;
    cout<<endl;

    for(auto pos = mp.begin(); pos!=mp.end();)
    {
        if(pos->first <= 20)
            mp.erase(pos++);
        else
            ++pos;
    }

    for(auto& elem : mp)
        cout<<"  first = "<<elem.first<<"  second = "<<elem.second<<endl;

    return 0;
}