如何获取std :: map的前n个元素

如何获取std :: map的前n个元素

问题描述:

由于在C ++中没有.resize()成员函数std :: map我想知道,如何得到一个std :: map最多有n个元素。

Since there is no .resize() member function in C++ std::map I was wondering, how one can get a std::map with at most n elements.

显而易见的解决方案是创建一个从0到n的循环,并使用第n个迭代器作为std :: erase()的第一个参数。

The obvious solution is to create a loop from 0 to n and use the nth iterator as the first parameter for std::erase().

如果有任何解决方案不需要循环(至少不在我的用户代码中),并且更多的是STL的方式去。

I was wondering if there is any solution that does not need the loop (at least not in my user code) and is more "the STL way to go".

您可以使用 std :: advance(iter,numberofsteps)