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

Since in C ++ std :: map there is no .resize () function, I was wondering how to get std :: map with max n elements.

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

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

+6
c ++ resize stdmap
source share
5 answers

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

+13
source share

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

 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()); } 
+3
source share

The string std :: map is not a list. There are no "first n" elements.

BTW: Iterators become invalid if the container is modified.

If you really need a smaller map, you can repeat it and add all the elements up to the nth in the new map.

+1
source share

The proper way to do this is to use std :: advance. But here's a fun (slow) way to "use the resizing on the map." In general, this trick can be used for other things working on the vector, but not on the 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()); 
+1
source share

Why do you want to resize the card?

Elements on the map are not saved in any order - the first "n" actually means nothing

Editing:
Interestingly, std :: map has an order, not sure how useful this concept is.
Are the entries in the same sorting order as the keys?
What does it mean? If you have names entered by SSN, does that mean that names are stored in numerical order of SSN?

0
source share

All Articles