删除地图的最后5个元素

时间:2015-08-22 21:38:57

标签: c++

我想从std :: map中删除最后5个元素。

一种方法是:

  for(int i=0; i < 5; i++)
  {
    map<string, LocationStruct>::iterator it = myLocations.end();
    it--; 
    myLocations.erase(it);
  }  

如果没有循环,有没有一种好方法呢?

谢谢,

4 个答案:

答案 0 :(得分:3)

您可以使用std :: prev功能为您进行导航:

m.erase(prev(m.end(), 5), m.end());

答案 1 :(得分:3)

可编程演示的一种方法。请注意,因为map迭代器不是随机访问迭代器,所以在调用std::prev()期间可能会涉及到一个循环。

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

using namespace std::string_literals;

std::map<int, std::string> m = {
    { 0, "zero"s },
    { 1, "one"s },
    { 2, "two"s },
    { 3, "three"s },
    { 4, "four"s },
    { 5, "five"s }
};

auto main() -> int
{
    for (const auto& entry : m) {
        std::cout << entry.first << ", " << entry.second << std::endl;
    }

    // erase operation here
    m.erase(std::prev(m.end(), 5), m.end());

    std::cout << "\nafter erase \n\n";
    for (const auto& entry : m) {
        std::cout << entry.first << ", " << entry.second << std::endl;
    }

    return 0;
}

预期产出:

0, zero
1, one
2, two
3, three
4, four
5, five

after erase 

0, zero

答案 2 :(得分:1)

使用范围删除

auto i = m.begin();
std::advance(i, (m.size() - 5) );
m.erase( i, m.end() );

答案 3 :(得分:0)

据我所知,std :: map有正常的访问迭代器,所以每次都必须遍历到最后一个元素才能从内存中删除它。