mardi 23 mars 2021

c++ update map member in class automatically

I'd like to link the map in the class with other members in the same class. Here I have B.C which defines a class Category. In my main function(in file A.C), I'd like to change the members in the map via

 mycategory.my_vectors["my_vect1"] = outer_vector;

in the meanwhile, I'd like to update the mycategory.my_vect1 automatically, instead of using mycategory.map_update(); in the main function.

If I remove mycategory.map_update();, the output is:

0
0x103acc0
my_vect1 0x103acc0
my_vect2 0
0

means only mycategory.my_vectors["my_vect1"] got updated, but mycategory.my_vect1 didn't change. How to do that?

B.C

#include <map>
#include <vector>
#include <string>
class Category{

public:

  std::vector<float> *my_vect1, *my_vect2;
  
  std::map<std::string, std::vector<float>*> my_vectors;

  void map_init(){
    my_vectors["my_vect1"]  = my_vect1;
    my_vectors["my_vect2"]  = my_vect2;
  }

  void map_update(){
    my_vect1 = my_vectors["my_vect1"];
    my_vect2 = my_vectors["my_vect2"];
  }
  
  Category(){
    map_init();
  }
  
};

A.C

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include "B.C"
int main(){

  Category mycategory;

  std::cout<<mycategory.my_vectors["my_vect1"]<<std::endl;  

  std::vector<float> * outer_vector = new std::vector<float>;
  outer_vector->push_back(3.14159);

  mycategory.my_vectors["my_vect1"] = outer_vector;
  std::cout<<mycategory.my_vectors["my_vect1"]<<std::endl;  

  for(auto &vect : mycategory.my_vectors){
    std::cout<<vect.first<<" "<<vect.second<<std::endl;
  }
  mycategory.map_update();
  std::cout<<mycategory.my_vect1<<std::endl;  
  
}

Aucun commentaire:

Enregistrer un commentaire