我想将一个类的对象存储在std::map
中。下面是一个工作示例展示如何,我这样做currenty将对象存储在std :: map中
#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;
}
我有两个问题,这个例子:
这就是专业的C++ - 的方式存储在上面的
std::map
对象案件?或者我应该创建一个指向A
的对象并存储该对象?我喜欢第一个(当前)选项,因为我不必担心使用new
和delete
自己的内存管理 - 但最重要的是我想正确地做事。我该如何去调用一个成员函数,如
result_map[0]
?我天真地试图result_map[0].output_a()
,但给我的错误:error: no matching function for call to ‘A::A()’
你可以使用语法'result_map [ITER] = A;'。 –
_“...但是这给了我一个错误”_:总是有用的在您的文章中包含错误。 –
1.是的,2.“但是这给了我一个错误。” - 什么错误?在尝试执行'result_map [key] .function()'时,我没有错误'' – Fureeish