Hi, me again (last one today I promise ) So the situation is : I am trying to create a class that holds some info and allow others to query the data structures inside my class but not to change it. I figured, the best way to achieve this would be just to set a pointer to the variable and be done with it, but it does not work like that . example :
Code:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class X{
unordered_map<int,vector<int>> x;
public:
const unordered_map<int,vector<int>> *c;
X(int);
void print();
};
X::X(int y){
x.clear();
for(int i = 0;i< 3;i++){
x[0].push_back(y+i);
}
c=&x;
}
void X::print(){
for(int i = 0;i< 3;i++)
cout << x[0][i] << "\n";
}
int main (){
X a(6);
a.print();
cout << (*a.c)[0][1] << "\n";
}
if i remove remove const it works , but then x can be modified and i do not wish that. Now if i repeat all jist with vectors like this :
Code:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class X{
vector<int> x;
public:
const vector<int> *c;
X(int);
void print();
};
X::X(int y){
x.clear();
for(int i = 0;i< 3;i++){
x.push_back(y+i);
}
c=&x;
}
void X::print(){
for(int i = 0;i< 3;i++)
cout << x[i] << "\n";
}
int main (){
X a(6);
a.print();
cout << (*a.c)[1] << "\n";
}
i get exactly what i want . Why can't I do the same with the above map/hash table?
Is there a better way to do this?
thnx