1
votes

Project should give as random number but that is not important, then that number of random find in first map and add into second map.

int rand = 2;
QPixmap pixmap1 = QPixmap (":/imag/sedam_one.jpg");
QPixmap pixmap2 = QPixmap (":/imag/gedam_one.jpg");
QPixmap pixmap3 = QPixmap (":/imag/tedam_one.jpg");
QMap<int, QPixmap> map;
map.insert(1, pixmap1);
map.insert(2, pixmap2);
map.insert(3, pixmap3);
QMap<int, QPixmap> myMap;
myMap.insert(map.key(rand), map.value(rand));
2
if "rand" isn't a valid key in "map" this will fail - cppguy
Do you want to take key-value pairs randomly from one map and then put them into another? Is that your question? - mhcuervo
What about myMap.insert(rand, map.take(rand)) ? -> Providing that you make sure rand is a valid key first. - mhcuervo

2 Answers

0
votes

Your code will be different based on the behavior you want when rand is not a valid key.

  1. If you want to ignore the key if it is not there in map, you would use:

    if ( map.find(rand) != map.end() )
    {
      myMap.insert(map.key(rand), map.value(rand));
    }
    
  2. If you want a default-constructed value when the key is not there map, you would not create the if check from the above code and simply use the code that you have:

    myMap.insert(map.key(rand), map.value(rand));
    
0
votes

Here's one way to do that:

  int rand = 2;
 QPixmap pixmap1 = QPixmap (":/imag/sedam_one.jpg");
 QPixmap pixmap2 = QPixmap (":/imag/gedam_one.jpg");
 QPixmap pixmap3 = QPixmap (":/imag/tedam_one.jpg");
 QMap<int, QPixmap> map;
 map.insert(1, pixmap1);
 map.insert(2, pixmap2);
 map.insert(3, pixmap3);
 QMap<int, QPixmap> myMap;
 myMap.insert(rand, map.value(rand));

Notice the last line. map.key(rand) should be just rand because the method map.key() requires that you put in a value such as a QPixmap