I'd like to store objects of a class in an std::map. Here is a working example showing how I am doing it currenty
#include <iostream>
#include <map>
class A
{
private:
int a;
std::string b;
public:
A(int init_a, std::string init_b) : a(init_a), b(init_b){};
void output_a() {std::cout << a << "\n";}
};
int main()
{
std::map<size_t, A> result_map;
for (size_t iter = 0; iter < 10; ++iter)
{
A a(iter, "bb");
result_map.insert(std::make_pair(iter, a));
}
return 0;
}
I have two question to this example:
Is this the professional C++-way to store objects in an
std::mapin the above case? Or should I create a pointer to an object ofAand store that instead? I like the first (current) option as I don't have to worry about memory management myself by usingnewanddelete- but most importantly I'd like to do things properly.How would I go about calling a member function of, say,
result_map[0]? I naively triedresult_map[0].output_a(), but that gave me the error:error: no matching function for call to ‘A::A()’
result_map[iter] = a;.result_map[key].function()Ahas no default constructor but has one that requires 2 parameters.std::map::operator[], not to invoke member function.