lundi 7 février 2022

Custom class range based for-loop over a 2D map

I have the following class MyClass that contains a 2D map (std::map<std::string, std::map<std::string,double>>).

I would like to know if it is possible to implement the MyClass::begin() MyClass::end() functions for MyClass in order to have a range-based for loop (as in the code below) that would allow me to print all doubles contained in that 2D map.

To be clear I do not want to introduce double for loops, I would like a single for() loop
(The aim after is putting the map mp as a private member of MyClass and only allow to loop over the class through that range-based for loop)

Many thanks in advance!

#include<string> 
#include<map> 
#include<iostream>

class MyClass{
  public:
  MyClass() {} ;
  ~MyClass(){}; 
  std::map<std::string, std::map<std::string,double>> mp = {};
};


int main()
{
  MyClass mycls ; 
  mycls.mp["a"]["a"] = 1;
  mycls.mp["a"]["b"] = 2; 
  mycls.mp["a"]["c"] = 3;
  mycls.mp["b"]["a"] = 4;
  mycls.mp["b"]["b"] = 5; 
  mycls.mp["b"]["c"] = 6;
  mycls.mp["d"]["a"] = 7;
  mycls.mp["d"]["b"] = 8; 
  mycls.mp["d"]["c"] = 9;
  mycls.mp["e"]["a"] = 10;
  mycls.mp["e"]["b"] = 11; 
  mycls.mp["e"]["c"] = 12;

  for (std::pair<const std::string, double> &obj : mycls){
    std::cout << "obj.second = " << obj.second << std::endl; 
  }

  return 0 ; 
}

Aucun commentaire:

Enregistrer un commentaire