你如何使用映射值?

时间:2014-12-15 23:26:03

标签: c++ oop pointers dictionary polymorphism

我有

的映射
map <ShapeType, vector <Shape *> > shapeMap;

我在地图中插入随机形状。 我想使用方法(Draw)作为映射值。当我浏览地图时,你如何去做呢?

void RandomAttributes(Shape *shape);

// declare our objects, and pointers for downcasting
MyRect rObj, *rPtr;
MyTriangle tObj, *tPtr;
MyCircle cObj, *cPtr;



void main()
{
    int shapes; // loop index

    // seed the random number generator
    srand((unsigned int)time(0));

    // allow the user time to move the console window away
    // from the FilledShapes window are
    cout << "Move this window to the lower right of the screen, and press ENTER to continue:\n";
    cin.get();



    // define our array size
    const int baseSize = 3;

    // create an vector of base class pointers
    vector <Shape *> baseShape(baseSize);

    // initialize our vector of base class pointers
    //initialize vector of shapes
    baseShape[0] = &rObj; // a MyRect IS A Shape
    baseShape[1] = &tObj;   // a MyTriangle IS A Shape
    baseShape[2] = &cObj; // a MyCircle IS A Shape

    enum ShapeType {
        MyRectangle = 0,
        MyTriangle = 1,
        MyCircle = 2
    };

    //map
    map <ShapeType, vector <Shape *> > shapeMap;


    for (int i = 0; i<PROGRAM_RUN; i++)
    {
        // clear the window
        // note that I can use ANY instance of a MyRect
        // object to clear the window
        baseShape[0]->ClearScreen();

        int rNum = rand() % 3;

        //CREATING RANDOM SHAPES
        // choose random parameters for each rectangle
        RandomAttributes(baseShape[rNum]);

        //insert shape
        shapeMap.insert(pair<ShapeType, vector <Shape *>>(ShapeType(rNum), baseShape)) ;

    }

    for (map <ShapeType, vector <Shape *> >::iterator pos = shapeMap.begin(); pos != shapeMap.end(); ++pos)
    {
       //DOES NOT WORK
        pos->second->Draw();
    }

}

我目前的实施:

    for (map <ShapeType, vector <Shape *> >::iterator pos = shapeMap.begin(); pos != shapeMap.end(); ++pos)
    {
       //DOES NOT WORK
        pos->second->Draw();
    }

}

如何遍历地图并使用draw方法,如下所示: 我想实现的映射值如下:

//baseShape[0]->Draw();
//baseShape[1]->Draw();
//baseShape[2]->Draw();

如果我的地图数据类型是baseShape矢量指针。

2 个答案:

答案 0 :(得分:1)

您建议的内容不起作用,因为pos->second不是Shape*,而是vector<Shape*&gt;。你也必须迭代第二个:

for (map <ShapeType, vector <Shape *> >::iterator pos = shapeMap.begin(); 
     pos != shapeMap.end(); ++pos)
{
    vector<Shape*>& shapes = pos->second;

    for (size_t i = 0; i < shapes.size(); ++i) {
        shapes[i]->Draw();
    }
}

或者如果你可以使用C ++ 11:

for (auto& pr : shapeMap) {
    for (auto shape : pr.second) {
        shape->Draw();
    }
}

答案 1 :(得分:0)

取消引用pos迭代器的结果是pair<ShapeType, vector<Shape*>>&,因此其second成员是vector<Shape*> - 换句话说,您需要遍历所有元素地图中的每个值,例如

for (auto& kv : shapeMap)
{
    for (auto shape : kv.second)
    {
        shape->Draw();
    }
}