2017-07-26 66 views
0

我想将一个类的对象存储在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; 
} 

我有两个问题,这个例子:

  1. 这就是专业的C++ - 的方式存储在上面的std::map对象案件?或者我应该创建一个指向A的对象并存储该对象?我喜欢第一个(当前)选项,因为我不必担心使用newdelete自己的内存管理 - 但最重要的是我想正确地做事。

  2. 我该如何去调用一个成员函数,如result_map[0]?我天真地试图result_map[0].output_a(),但给我的错误:error: no matching function for call to ‘A::A()’

+0

你可以使用语法'result_map [ITER] = A;'。 –

+2

_“...但是这给了我一个错误”_:总是有用的在您的文章中包含错误。 –

+0

1.是的,2.“但是这给了我一个错误。” - 什么错误?在尝试执行'result_map [key] .function()'时,我没有错误'' – Fureeish

回答

6

Is this the professional C++-way to store objects in an std::map in the above case?

它是好的,简单的代码可能是:

result_map.emplace(iter, A(iter, "bb")); 

,你应该使用任何你找到更易读。顺便说一句,调用整数计数器iter不是一种编写可读代码的方法。

How would I go about calling a member function of, say, result_map[0]?

您更好地使用std::map::find

auto f = result_map.find(0); 
if(f != result_map.end()) f->output_a(); 

问题,你的情况operator[] - 它能够创建和实例,如果对象不与索引中存在,但你没有默认构造函数为A

0

1- 这取决于:如果您的课程可以复制,并且您不担心复制对象到地图中的性能问题,那么这是一个很好的方法。但是,如果说你的类持有任何不可变的数据(例如std::mutex),你必须使用一个指针,因为C++自动生成的复制构造函数会生成不正确的形式,所以它只是无法复制类

2- result_map.at(0).output_a()result_map.at(0)->output_a()如果你使用的地图指针