Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first n elements of a std::map

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.

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

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".

like image 357
Norbert Avatar asked Nov 27 '09 14:11

Norbert


3 Answers

You can use std::advance( iter, numberofsteps ) for that.

like image 69
xtofl Avatar answered Oct 22 '22 04:10

xtofl


Universal solution for almost any container, such as std::list, std::map, boost::multi_index. You must check the size of your map only.

template<class It>
It myadvance(It it, size_t n) {
   std::advance(it, n);
   return it;
}

template<class Cont>
void resize_container(Cont & cont, size_t n) {
    cont.erase(myadvance(cont.begin(), std::min(n, cont.size())), 
                 cont.end());
}
like image 40
Alexey Malistov Avatar answered Oct 22 '22 04:10

Alexey Malistov


The correct way for this is to use std::advance. But here is a funny (slow) way allowing to 'use resize on map'. More generally, this kind of trick can be used for other things working on vector but not on map.

map<K,V> m; //your map
vector< pair<K,V> > v(m.begin(), m.end());
v.resize(n);
m = map<K,V>(v.begin(),v.end());
like image 43
Alink Avatar answered Oct 22 '22 02:10

Alink