Fill the contents of C ++ maps in the loop area

I am trying to populate the contents of a C ++ map within a loop area.

#include <set>
#include <map>

map<int, set<int> > maps;

for (int i=0; i<10; i++) {
   set<int> seti;    // content: a set of integers
   seti.insert(i);
   seti.insert(...);
   maps.insert ( pair<int,set<int> >(i,seti) );
}

Question: does maps.insert copy the contents of a pair? If the pair instance is invalid after each area of ​​the loop, then such code should fail.

How to properly create the contents of a map (with a pointer and a new instance?) And how to properly clear a map?

thanks for any suggestion about best practices.

--- UPDATE ---

map<int, set<int> >::iterator it;
int k      = (*it).first;     
set<int> v = (*it).second;       

is now "v" also copied from a real instance stored on the map?
if so, then I don’t have the ability to "directly" update the contents of the map.

+3
source share
5 answers

, []. ,

#include <set>
#include <map>

map<int, set<int> > maps;

for (int i=0; i<10; i++) {
   maps[i].insert(i);
}
+5

, . , ​​ for. , , make_pair:

#include <set> 
#include <map> 

map<int, set<int> > maps; 

for (int i=0; i<10; i++) { 
   set<int> seti;    // content 
   seti.insert(i); 
   maps.insert ( std::make_pair(i,seti) ); 
} 

, , .

: . , , .

+4

, , . - regular type . ( , ) , .

+1

, maps

map<int, set<int> > maps;

, , .

:

  • set of int 's
  • , set map.

typedef std::set< int > IntSet;
typedef std::map< int, IntSet > MapOfIntSet;

MapOfIntSet myMap;     // container

for( int i = 0; i < N; ++i ) {
    IntSet intSet;
    for( int j = i + 1; j < N; ++j ) {
        intSet.insert( j );
    }

    // Both the following line does the same, any one can be used
    // myMap.insert( make_pair( i, intSet ) );
    myMap[ i ] = intSet;
}

A .

+1

Yes, the whole set is copied internally, which is a performance bottleneck. Because of this, I do not like the proposed solutions. And also, as you request to use pointers, you can use safely boost::shared_ptr. The code might look like this:

#include <set>
#include <map>
#include <boost/shared_ptr.hpp>

// I add typedefs for clarity
typedef boost::shared_ptr< set<int> > set_ptr;

using namespace std;

map<int, set_ptr > maps;

for (int i=0; i<10; i++) {
   set_ptr seti( new set<int>());    // content
   seti->insert(i);
   maps.insert ( std::make_pair(i,seti) );
}

Please note that now you only copy safe pointers that are deleted when deleted maps.

0
source

Source: https://habr.com/ru/post/1770341/


All Articles