Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ maps with variables

Is it possible to create a dynamically changing map? For example, i want to use it in the for loop, and use i as a variable in map value:

uint8_t i{};

std::map<uint8_t, int16_t> substitutions{
  {0, array[i][0]},
  {1, array[i][1]}, 
  {2, array[i][2]}, 
  {3, array[i][0] * array[i][1]}, 
  {4, array[i][0] * array[i][2]}, 
  {5, array[i][1] * array[i][2]}, 
  {6, array[i][0] * array[i][1] * array[i][2]}, 
  {7, pow(array[i][0], 2)}, 
  {8, pow(array[i][1], 2)}, 
  {9, pow(array[i][2], 2)}};

for (i = 0; i < 3; i++)
{
  anmSum += substitutions.find(a)->second * substitutions.find(b)->second;
}

Right now it just substitutes 0 (because i = 0) and leaves it at that.
Maybe instead of fixed values use lambda-function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’d probably solve your problem by not using a map at all. I’d use a switch statement instead (it should be slightly faster):

for (uint8_t i = 0; i < 3; i++)
{
  auto substitute = [i](uint8_t value)
  {
    switch (value)
    {
    case 0: return array[i][0];
    case 1: return array[i][1];
    case 2: return array[i][2];
    case 3: return array[i][0] * array[i][1]};
    case 4: return array[i][0] * array[i][2]};
    case 5: return array[i][1] * array[i][2]};
    case 6: return array[i][0] * array[i][1] * array[i][2]};
    case 7: return pow(array[i][0], 2)};
    case 8: return pow(array[i][1], 2)};
    case 9: return pow(array[i][2], 2)};
    default: throw std::invalid_argument("invalid value");
    };
  };
  anmSum += substitute(a) * substitute(b);
}

Using your approach you’d have to make your map contain some sort of function pointer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading