C++ map 容器

标签 c++ dictionary this containers

<分区>

我正在学习使用 map 容器,我可以看到逻辑,我们可以在插入任何对象时定义键和值。我也知道我们可以用这些容器插入对,并且可以通过 .first 和 .second 访问内容。但是我无法理解这段代码,如果可以的话需要有人启发我:

A类.h

#include"ClassB"
#include"ClassC"

class A
{
public:
    template<typename T>
    void foo1(classC::ID id);
private:
    ClassB::Ptr someFunction(classC::ID id);
private:
    //map 
    std::map<class::ID, std::function<classB::Ptr()>> mapName;
}

template<typename T>
void ClassA::foo1(classC::ID id)
{
    mapName[id] = [this]()  // <-------------- that [this]() ???
    {                       // Is this calling for that
                            // function<class::Ptr()> inside map??
        //TODO
    }
}

B类.h

#include"ClassC"

class B
{
    typedef std::unique_ptr<ClassB> Ptr;
public:
    classB(param1 from other classes , param2 from other classes);
    ....
}

类C.h

namespace States
{
    enum ID
    {
        foo,
        foo1,
        ...
    }
 }        

谢谢

最佳答案

在您的示例中,“奇怪的部分”实际上与映射和访问器无关。这个 this{/*TODO*/} 是一个 C++ lambda 表达式——一个没有参数的简单函数,可以访问“this”指针。

本例中 map 的使用完全是顺序的——您只需访问带有键 [id] 的元素(如果它不存在则创建它),然后将 lambda 函数(值)分配给该键。如果查看映射的定义,您会发现值类型实际上是 std::function。有关此模板的更多信息,您可以在 http://www.cplusplus.com/reference/functional/function/ 下找到

关于C++ map 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28630897/

相关文章:

c++ - 如何使数组无效?

swift - 在 Swift 中制作结构字典时必须导入 Foundation 吗?

python - 在 python 中实现 T9 字典时输出错误

javascript - 对 "softBind"函数如何工作的困惑

java this 关键字

c++ - 各种标记之前的预期主表达式

c++ - OpenCV propId 值位于何处?

c++ - 虚拟析构函数有什么用?

javascript - 在 JavaScript 中将方法作为参数传递

python - 我应该使用类还是字典?