user1056903 user1056903 - 28 days ago 14
C++ Question

Fill array with elements at certain positions

Given is a

std::array
which contains instances of sub classes of
IMyClass
:

std::array<std::shared_ptr<IMyClass>, 20> myArr;


At index position 0, 5 and 10

std::make_shared<RareSubClass>()


should be assigned, on all other indices

std::make_shared<FrequentSubClass>()


What is the best way to achieve this?

Answer

It's easy to initialize that array at runtime using a small helper function:

 void init_array(std::array<std::shared_ptr<IMyClass>, 20>& arr) {
      int slot = 0;
      for(auto& subclass : arr) {
         switch(slot) {
         case 0:
         case 5:
         case 10:
             subClass = std::make_shared<RareSubClass>();
             break;
         default:
             subClass = std::make_shared<FrequentSubClass>();
             break;
         }
         ++slot;
      }
 }